Become a member
to unlock all features

Level Up!

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


    Build and Validate a Form in Vanilla React

    react-nativeReact Native

    Learn how to make forms and validate form fields using the onBlur event without any external React helper library/component.

    With this knowledge, you will understand what problem the next lesson is trying to solve.



    Become a Member to view code

    You must be a Pro 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
    orLog In




    Instructor: Let's start with a simple user form, which has a single field. The field is made of a label for user name and input for receiving the username. The input also needs to have a value prop, which you can pass a state item to.

    Let's go ahead and create the state. Then, add a button that would submit the form. We need to make the input a controlled element for adding on a change handler. We can name the function handleUserNameChange.

    Then we can implement this handler. Basically, what we need to do here is to update this state whenever the value changes. We can do this.setState, user name, and then the new value coming from the event object, a value.

    We can pass in the event object, the function. We can also add a simple validation using the onBelow event, user name below. Then we can implement this function as well.

    What we need to do here is, if the value doesn't exist, then we can set the state of an errors object. An errors object that has a user name field, so user name is required. If that's not the case, then we can just do the same thing, but leave the value empty.

    We also need to go ahead and create the errors object and the user name field. I think I misspelled the onBelow event. laughs It should be onBelow, not onBelew. We can simply show the error message in a paragraph.

    We can change the color of the text to red, just to show that some error. You can ead to the output, click an input, and click outside to get the user name of a validation error, since the field is empty. Once you start typing out and click out once more, the validation error disappears.

    The last thing that we need to do is to add an onSubmit handler to the form, handleSubmit. Then we can create the handleSubmit method, which receives the event object as well, and just basically logs out the value of the state.

    If you pull up the console, fill out the form, submit, we should see the user name value and the errors object.