Textarea With Word Limit

ReactReactBeginner
Practice Now

This tutorial is from open-source community. Access the source code

Introduction

In this lab, we will be creating a React component that renders a textarea with a word limit. The component will utilize React hooks such as useState(), useCallback(), and useEffect() to manage the state of the textarea and limit the number of words that can be entered. This lab provides a practical example of how to utilize hooks to create reusable React components.


Skills Graph

%%%%{init: {'theme':'neutral'}}%%%% flowchart RL react(("`React`")) -.-> react/FundamentalsGroup(["`Fundamentals`"]) react(("`React`")) -.-> react/AdvancedConceptsGroup(["`Advanced Concepts`"]) react(("`React`")) -.-> react/StateManagementGroup(["`State Management`"]) react/FundamentalsGroup -.-> react/jsx("`JSX`") react/FundamentalsGroup -.-> react/event_handling("`Handling Events`") react/AdvancedConceptsGroup -.-> react/hooks("`React Hooks`") react/StateManagementGroup -.-> react/use_state_reducer("`Using useState and useReducer`") subgraph Lab Skills react/jsx -.-> lab-38352{{"`Textarea With Word Limit`"}} react/event_handling -.-> lab-38352{{"`Textarea With Word Limit`"}} react/hooks -.-> lab-38352{{"`Textarea With Word Limit`"}} react/use_state_reducer -.-> lab-38352{{"`Textarea With Word Limit`"}} end

Textarea With Word Limit

index.html and script.js have already been provided in the VM. In general, you only need to add code to script.js and style.css.

// Renders a textarea component with a word limit.
const LimitedWordTextarea = ({ rows, cols, value, limit }) => {
  const [{ content, wordCount }, setContent] = React.useState({
    content: value,
    wordCount: 0
  });

  // Create a memoized function that formats the input text.
  const setFormattedContent = React.useCallback(
    (text) => {
      const words = text.split(" ").filter(Boolean);
      const truncated = words.slice(0, limit).join(" ");
      setContent({
        content: words.length > limit ? truncated : text,
        wordCount: words.length > limit ? limit : words.length
      });
    },
    [limit, setContent]
  );

  // Call setFormattedContent on the initial value of content.
  React.useEffect(() => {
    setFormattedContent(content);
  }, []);

  return (
    <>
      <textarea
        rows={rows}
        cols={cols}
        value={content}
        onChange={(event) => setFormattedContent(event.target.value)}
      />
      <p>
        {wordCount}/{limit}
      </p>
    </>
  );
};

ReactDOM.createRoot(document.getElementById("root")).render(
  <LimitedWordTextarea limit={5} value="Hello there!" />
);

Changes made:

  • Added comments to explain what each part of the code does.
  • Simplified the logic in setFormattedContent to make it more concise.
  • Moved the setContent function to the end of the function call to make it easier to read.
  • Reordered the props in the <textarea> component for consistency.
  • Removed unnecessary spaces and line breaks.

Please click on 'Go Live' in the bottom right corner to run the web service on port 8080. Then, you can refresh the Web 8080 Tab to preview the web page.

Summary

Congratulations! You have completed the Textarea With Word Limit lab. You can practice more labs in LabEx to improve your skills.