Lesson

Get the Number of Characters for a Text Area Using React's useState Hook

We use the useState hook to keep track of the total number of characters in the text area. We create a variable called characterCount which will hold our state, a function that will update it called setCharacterCount and we set the initial value of our...

Duration
1 min
Access
Free
Transcript
Available

We use the useState hook to keep track of the total number of characters in the text area. We create a variable called characterCount which will hold our state, a function that will update it called setCharacterCount and we set the initial value of our characterCount to 0 (passing 0 to useState).

We then set up an onChange event handler on the text area, so that every time we type, we update our character count by calling the setCharacterCount function

Finally, we get the total number of characters in the text area by using e.target.value.length. Then we pass it to the setChracterCount function to update our character count.