Textarea with character limit
Renders a textarea component with a character limit.
- Use the
useState()
hook to create thecontent
state variable. Set its value to that ofvalue
prop, trimmed down tolimit
characters. - Create a method
setFormattedContent
, which trims the content down tolimit
characters and memoize it, using theuseCallback()
hook. - Bind the
onChange
event of the<textarea>
to callsetFormattedContent
with the value of the fired event.
const LimitedTextarea = ({ rows, cols, value, limit }) => { const [content, setContent] = React.useState(value.slice(0, limit)); const setFormattedContent = React.useCallback( text => { setContent(text.slice(0, limit)); }, [limit, setContent] ); return ( <> <textarea rows={rows} cols={cols} onChange={event => setFormattedContent(event.target.value)} value={content} /> <p> {content.length}/{limit} </p> </> ); }; ReactDOM.createRoot(document.getElementById('root')).render( <LimitedTextarea limit={32} value="Hello!" /> );