⚠️ This lesson is retired and might contain outdated information.

Validate a React Input After the User Leaves the Input with the useState Hook

Gosha Arinich
InstructorGosha Arinich
Share this video with your friends

Social Share Links

Send Tweet

You can validate your input and that's great — but screaming "you are wrong" before the user has had a chance to interact with it is not a good user experience.

Learn to display the validation status only after the user focuses out of the input. We will achieve that by creating a separate state variable called touched which will hold whether the user focused out of the input, which we'll later use to conditionally render the validation status.

Note: you need to be using a version of React that supports Hooks (versions 16.8.0 and higher) to follow this lesson.

Instructor: [00:00] We have a simple React application that renders a name input. The value for that input is stored in a state variable called name. Whenever that value changes, a handleNameChange function updates the state variable.

[00:13] We also check whether the input is valid. We render its validation status right away. We can see that the red cross mark is displayed right next to the input even before we had a chance to type something into the input. That's not really a good user experience. We want to fix that.

[00:33] We want to show the validation status only after the user has had a chance to interact with the input. To achieve that, we'll create a new state variable called touched. It will hold a Boolean indicating whether the user has blurred the input. We'll use the onBlur prop of the input to set touched to true.

[00:54] Now we'll change the conditional to only display the validation status if the input has been touched. Otherwise, we will not display anything. We can see that nothing is displayed next to the input, but if we touch it and leave the input, we can see that its validation status is being displayed.