Update LimitedTextarea.md

This commit is contained in:
Angelos Chalaris
2019-02-12 20:33:57 +02:00
committed by GitHub
parent 125e61fead
commit 46b0de9ba0

View File

@ -2,34 +2,29 @@
Renders a textarea component with a character limit. Renders a textarea component with a character limit.
Use the `value` and `limit` props to pass in the initial `content` and the `limit` values for the LimitedTextArea component. Use the `React.useState()` hook to create the `content` state variable and set its value to `value`.
Create a method, `handleChange`, which trims the `event.target.value` data if necessary and updates `content` with the new entered content. Create a method `setFormattedContent`, which trims the content of the input if it's longer than `limit`.
In the`render()` method, use a`<div>` to wrap both the`<textarea>` and the `<p>` element that displays the character count and bind the `onChange` event of the `<textarea>` to the `handleChange` method. Use the `React.useEffect()` hook to call the `setFormattedContent` method on the value of the `content` state variable.
Use a`<div>` to wrap both the`<textarea>` and the `<p>` element that displays the character count and bind the `onChange` event of the `<textarea>` to call `setFormattedContent` with the value of `event.target.value`.
```jsx ```jsx
function LimitedTextArea(props) { function LimitedTextarea({ rows, cols, value, limit }) {
const { rows, cols, value, limit } = props; const [content, setContent] = React.useState(value);
const setFormattedContent = text => { const setFormattedContent = text => {
text.length > limit ? setContent(text.slice(0, limit)) : setContent(text); text.length > limit ? setContent(text.slice(0, limit)) : setContent(text);
}; };
const [content, setContent] = useState(value); React.useEffect(() => {
// Run once to test if the initial value is greater than the limit
useEffect(() => {
setFormattedContent(content); setFormattedContent(content);
}, []); }, []);
const handleChange = event => {
setFormattedContent(event.target.value);
};
return ( return (
<div> <div>
<textarea <textarea
rows={rows} rows={rows}
cols={cols} cols={cols}
onChange={handleChange} onChange={event => setFormattedContent(event.target.value)}
value={content} value={content}
/> />
<p> <p>