Files
30-seconds-of-code/snippets/LimitedTextarea.md
Isabelle Viktoria Maciohsek 2af2490ca8 Bake dates into snippets
2021-06-13 19:44:42 +03:00

1.2 KiB

title, tags, firstSeen, lastUpdated
title tags firstSeen lastUpdated
LimitedTextarea components,state,callback,event,beginner 2018-10-19T09:11:59+03:00 2020-11-16T16:50:57+02:00

Renders a textarea component with a character limit.

  • Use the useState() hook to create the content state variable and set its value to that of value prop, trimmed down to limit characters.
  • Create a method setFormattedContent, which trims the content down to limit characters and memoize it, using the useCallback() hook.
  • Bind the 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')
);