DEV Community

Shanley Elizabeth
Shanley Elizabeth

Posted on

There's Something About Forms

Forms in React. I don't know how I became so fascinated with programming forms. I wrote a whole blog essay on forms in vanilla Javascript - just to move onto React and realize how much better and cleaner my code could be. So since I've learned more about forms in React, I figured I'd do a little blog about the differences between the two!

In vanilla JavaScript, creating a form involves setting up event listeners and manually managing form submission. But in React, we can take advantage of reusable components and some of React's very handy hooks, like the useState hook. By updating and storing the Form's data in a state variable with useState, we can handle the inputs updated value whenever a change occurs. Which also means, that we can access that data from anywhere in our app by using the state variable that the information is stored in. Previously, in vanilla Javascript, we would have to add event listeners on every input element. Which can become cumbersome. But with React, we can further abstract the form's data into an even more dynamic and simplified code.

Having the inputs update their State with every keystroke allows us the unique ability to add validations to our form. Validations are a way of controlling what kind of information is added into the form's input. They could make sure that you typed your password into the input with the correct format, or frustratingly remind you that your fat fingers accidentally typed "scaswello" instead of "Scaswell" as your username, again.

When submitting a form, React and vanilla Javascript are very similar. In vanilla JS, we find the form, attach an event listener to the form and then prevent default and handle all of the form data manually. With React, we put the onSubmit event handler on the form element and call a function handle the submission, also preventing default on the event object that is passed in as a parameter.
Let me provide an example:

Let's say we have our FormComponent... let's just call it "FormComponent" ... yay creativity!
We establish a base for our state which will be what it is before the user enters their own data:

const initialFormInfo = {
  name: "",
  likes: 0
};

const [formData, setFormData] = useState(initialFormInfo);
Enter fullscreen mode Exit fullscreen mode

We have our function handleChange(creative again!) that handles the "change" of keystroke in each input:

function handleChange(e) {
    setFormData((prevFormData) => {
      return {
        ...prevFormData,
        [e.target.name]: e.target.value,
      };
    });
  }
Enter fullscreen mode Exit fullscreen mode

As long as the input has a name prop, we can target that so that the prop referring to that specific input is populated there. And the value is what the user types into the input. We are making a copy of the previous state of the form data (which is initially empty) and then adding our new info to that object. Reminder that this info being entered is EVERY KEYSTROKE that we are making as a user inputting data. Handle change doesn't actually do anything with this information yet other than track it and update the state variable.

Here we have the function that handles the actual submit of the form:

 function handleSubmit(event) {
    event.preventDefault();
// whatever we want to do with the form information, post, patch, update the state of an array of data to include the new information that you just posted in the form etc.
}
Enter fullscreen mode Exit fullscreen mode

Within the return of the component, on your form and input, this is on way the syntax might look:

<form className="form" onSubmit={handleSubmit}>
      <h2>Add New Item</h2>
      <label >Name</label>
      <input
        type="text"
        id="name"
        name="name"
        value={formData.name}
        onChange={handleChange} />
Enter fullscreen mode Exit fullscreen mode

And tada! There is your React Form!

I think also with React's nature of having separate components for each functionality on a website allows for more organized code in general. Having a separate component specifically for a form makes it easier for someone else to come in and work on updating or editing the form at a later time because it's easier to see where all of the information is flowing to and from.

Overall, React gives us some very powerful tools to make efficient forms for our web applications. It's helps us make cleaner and more dynamic code, as well as allowing us to more easily add validations onto our form to influence the user input data.

Top comments (0)