Textarea with word limit
Renders a textarea component with a word limit.
- Use the
useState()hook to create a state variable, containingcontentandwordCount. Use thevalueprop and0as the initial values respectively. - Use the
useCallback()hooks to create a memoized function,setFormattedContent, that usesString.prototype.split()to turn the input into an array of words. - Check if the result of applying
Array.prototype.filter()combined withBooleanhas alengthlonger thanlimit. If it does, trim the input. Otherwise return the raw input, updating state accordingly in both cases. - Use the
useEffect()hook to call thesetFormattedContentmethod on the value of thecontentstate variable during the initial render. - Bind the
onChangeevent of the<textarea>to callsetFormattedContentwith the value ofevent.target.value.
const LimitedWordTextarea = ({ rows, cols, value, limit }) => {
const [{ content, wordCount }, setContent] = React.useState({
content: value,
wordCount: 0
});
const setFormattedContent = React.useCallback(
text => {
let words = text.split(' ').filter(Boolean);
if (words.length > limit) {
setContent({
content: words.slice(0, limit).join(' '),
wordCount: limit
});
} else {
setContent({ content: text, wordCount: words.length });
}
},
[limit, setContent]
);
React.useEffect(() => {
setFormattedContent(content);
}, []);
return (
<>
<textarea
rows={rows}
cols={cols}
onChange={event => setFormattedContent(event.target.value)}
value={content}
/>
<p>
{wordCount}/{limit}
</p>
</>
);
};