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
Become a member
to unlock all features

Level Up!

Access all courses & lessons on egghead today and lock-in your price for life.


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

    Gosha ArinichGosha Arinich

    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.



    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


    Instructor: 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.

    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.

    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.

    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.