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.
Mahmoud Abdelwahab: [0:00] Here we have a textarea with a placeholder value of "start typing!" and a text that will show the Total Number of characters.
[0:08] The first thing we need to do is import { useState } from "React" to keep track of the state of our component. Then, inside of our component, we're going to declare a new state variable called characterCount, a function that will update it, which we'll call setCharacterCount(), and we'll pass as the initial value of our state.
[0:27] To detect when the value of our textarea changes, we'll set up an onChange() handler. This is a function that takes an event as a parameter and will update our count by calling setCharacterCount every time the length of our text input changes.
[0:41] Finally, we'll use the characterCount variable to display the total number of characters. That's it. We're displaying the number of characters inside our textarea.
[0:50] To recap, we first imported useState from React to keep track of the state of the component. Then, we created a variable called characterCount and we set the initial value of our state to , since there won't be any characters.
[1:03] We added an onChange handler so that every time we type inside the text area, we update the characterCount by calling setCharacterCount and passing the total length of the text area. This way, we can get the total number of characters.
[1:20] Finally, we displayed the characterCount variable so that we can see it here.