Renders a textarea component with a character limit.
useState()
hook to create the content
state variable. Set its value to that of value
prop, trimmed down to limit
characters.setFormattedContent
, which trims the content down to limit
characters and memoize it, using the useCallback()
hook.onChange
event of the <textarea>
to call setFormattedContent
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.render(
<LimitedTextarea limit={32} value="Hello!" />,
document.getElementById('root')
);
Would you like to help us improve 30 seconds of code?Take a quick survey
React, Components
Renders a textarea component with a word limit.
React, Components
Renders a checkbox list that uses a callback function to pass its selected value/values to the parent component.
React, Components
Renders a file drag and drop component for a single file.