Join egghead, unlock knowledge.

Want more egghead?

This lesson is for members. Join us? Get access to all 3,000+ tutorials + a community with expert developers around the world.

Unlock This Lesson
1×
Become a member
to unlock all features
Autoplay

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

    Gosha ArinichGosha Arinich
    reactReact
    javascriptJavaScript

    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.

    Code

    Code

    Become a Member to view code

    You must be a Member to view code

    Access all courses and lessons, track your progress, gain confidence and expertise.

    Become a Member
    and unlock code for this lesson
    Transcript

    Transcript

    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.

    Discuss

    Discuss