⚠️ 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
Published 6 years ago
Updated 2 years ago

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.

egghead
egghead

Member comments are a way for members to communicate, interact, and ask questions about a lesson.

The instructor or someone from the community might respond to your question Here are a few basic guidelines to commenting on egghead.io

Be on-Topic

Comments are for discussing a lesson. If you're having a general issue with the website functionality, please contact us at support@egghead.io.

Avoid meta-discussion

  • This was great!
  • This was horrible!
  • I didn't like this because it didn't match my skill level.
  • +1 It will likely be deleted as spam.

Code Problems?

Should be accompanied by code! Codesandbox or Stackblitz provide a way to share code and discuss it in context

Details and Context

Vague question? Vague answer. Any details and context you can provide will lure more interesting answers!

Markdown supported.
Become a member to join the discussionEnroll Today