Character Counter
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
useState
hook to manage the text stateSolution Walkthrough for Character Counter
Spoiler Alert!
Don't read this unless you've already solved the problem.
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);
}
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} />
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>
CharacterCounter
component combines these important React concepts to create an interactive and responsive experience for users. 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.