Renders a textarea component with a word limit.
- Use the
useState()
hook to create a state variable, containingcontent
andwordCount
, using thevalue
prop and0
as 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 withBoolean
has alength
longer thanlimit
and, if so, trim the input, otherwise return the raw input, updating state accordingly in both cases. - Use the
useEffect()
hook to call thesetFormattedContent
method on the value of thecontent
state variable during the initial render. - Bind the
onChange
event of the<textarea>
to callsetFormattedContent
with 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> </> ); };
Examples
ReactDOM.render( <LimitedWordTextarea limit={5} value="Hello there!" />, document.getElementById('root') );
Recommended snippets
Renders a textarea component with a character limit.
Renders a file drag and drop component for a single file.
Renders a checkbox list that uses a callback function to pass its selected value/values to the parent component.