logo
logo

Character Counter

Medium

Character Counter

Medium

Create a simple Character Counter component that allows users to type in text and displays the number of characters in real-time.

Expectations:

  • Create a textarea element for users to type in text

  • Display the character count below the textarea in real-time

  • Use the
    useState
    hook to manage the text state

Console
Submit
Solution
00:00

Solution Walkthrough for Character Counter

Event Handling and Controlled Components:

React uses synthetic events to handle user interactions, such as changes to input fields. In this component, we need to respond to changes in the textarea's value. We create a function called
handleTextareaChange
that accepts an event object as its parameter. This event object contains information about the change, including the new value of the textarea. The function updates the
text
state variable with the updated value:
function handleTextareaChange(event) {
  setText(event.target.value);
}
We use the
handleTextareaChange
function as an event handler, attaching it to the
onChange
event of the textarea. Remember: this pattern of explicitly setting the value of an input field and providing an event handler to update the state is known as a controlled component in React:
<textarea value={text} onChange={handleTextareaChange} />

Real-time Updates and React's Re-rendering:

One of React's core features is its ability to efficiently re-render components when their state or props change. By connecting the
text
state to the textarea's value and the displayed character count, React will automatically re-render the component whenever
text
is updated. This ensures that the character count displayed below the textarea always reflects the current length of the text:
<p>Character count: {text.length}</p>

Putting It All Together:

The final
CharacterCounter
component combines these important React concepts to create an interactive and responsive experience for users.
The
useState
hook manages the component's state, while the controlled component pattern ensures that the textarea's value is always in sync with the state. React's re-rendering mechanism guarantees that the displayed character count updates in real-time as the user types in the textarea.