DEV Community

Josh Lee
Josh Lee

Posted on • Updated on

Using the useState Hook and Working with Forms in React.js.

Forms are the backbone of the Internet. Without them, it would be pretty difficult to make pass information between web pages. Luckily, working with forms in React.js is pretty easy.

Let’s build a basic form today using a functional component and using the useState hook.

First, let’s make a simple form in React.

import React from 'react'

const Form = () => {
  return (
    <form>
      <h1> Our Form </h1>
      <label htmlFor="title">Title</label>
      <input type="text" name="title" id="title" />

      <label htmlFor="body">Body</label>
      <textarea name="body" id="body"></textarea>
      <input type="submit" value="Submit" />
    </form>
  )
}

export default Form
Enter fullscreen mode Exit fullscreen mode

Is this an ugly form? Yes. Does it work for what we need it to do? Also, yes.

Forms in React work a little bit differently than you may be used to if you’re not used to working with React. When working with forms in React, it’s all about managing state and then using that state to populate your form.

Previously, when we used class-based components, state was pretty much built-in to them. But now, we can use functional components and use the useState hook to have a state in our functional component.

The first thing we need to do is import the useState hook from React.

import React, { useState } from 'react'
Enter fullscreen mode Exit fullscreen mode

Now we will create the object that holds our state. This syntax may look a little weird, but let me explain.

const Form = () => {
  const [formData, setFormData] = useState({
    title: "",
    body: ""
  })

....
Enter fullscreen mode Exit fullscreen mode

Here we’re setting up a variable for our state ‘formData’ and we are setting up a function that lets us change the values in formData, ‘setFormData.’

Whenever you need to change values inside your state, you need to use the setFormData() function.

Here, we are setting the default value to an object with the keys ‘title’ and ‘body’. We don’t have to use an object. We could have just as easily done this, but I prefer using an object because it makes things easier down the line.

const [title, setTitle] = useState("")

const [body, setBody] = useState("")
Enter fullscreen mode Exit fullscreen mode

In React, we get the form’s values from the state, so we need to set the values on our inputs.

<label htmlFor="title">Title</label>
<input value={formData.title} type="text" name="title" id="title" />
<label htmlFor="body">Body</label>
<textarea value={formData.body} name="body" id="body"></textarea>
Enter fullscreen mode Exit fullscreen mode

If you try typing in your inputs, you’ll notice that they aren’t updating. Why is that? Think about it for a second: You set the values equal to our state object and the state object is just a few empty strings.

In order to update the value in the form, you have to update the value of the state. Here’s how we’re going to do that.

We’re going to add an onChange function that sets our state to the value of the input.

Here’s how:

<label htmlFor="title">Title</label>
<input onChange={(e) => setFormData({...formData, title: e.target.value})} value={formData.title} type="text" name="title" id="title" />
<label htmlFor="body">Body</label>
<textarea onChange={(e) => setFormData({...formData, body: e.target.value})}  value={formData.body} name="body" id="body"></textarea>
Enter fullscreen mode Exit fullscreen mode

Let’s really look at one of these functions to see what it’s doing:

onChange={(e) => setFormData({...formData, title: e.target.value})}
Enter fullscreen mode Exit fullscreen mode

First, this function is being called anytime the value of the input changes. Whenever you type something, this function fires.

This takes the event (e) and passes it to the setFormData() function. We can’t just set part of the formData, we have to set the full thing. So, we say, take whatever is in the form (…formData) and set that and then add the key and value title: e.target.value.

Now to test out our form, let’s console.log our values. Add a handleSubmit() function to your form:

<form onSubmit={handleSubmit}>
Enter fullscreen mode Exit fullscreen mode

And then create the function handleSubmit()

const handleSubmit = (e) => {
    e.preventDefault()
    console.log(formData)

}
Enter fullscreen mode Exit fullscreen mode

Here, we’re just stopping the default behavior of loading the page and then logging out or data.

And there you have it. The basics of working with useState and forms in React. Now, all you have to do is hook this up to your api and send a post request with your data.

If you want to learn more about web development, make sure to follow me on Twitter.

Top comments (3)

Collapse
 
zzjyr1314 profile image
zzjyr1314

nice

Collapse
 
marimanger profile image
Mariia Bondarenko

how to use same logic with checkbox?

Collapse
 
muhammadnurulahsan profile image
Muhammad Nurul Ahsan • Edited

const [checkboxes, setCheckboxes] = useState({});
const handleChange = (event) => {
const { name, checked } = event.target;
setCheckboxes((prevCheckboxes) => ({
...prevCheckboxes,
[name]: checked,
}));
};
<label style={{ fontWeight: checkboxes[value] ? 'bold' : 'normal' }}>
<input type="checkbox" name={value} checked={checkboxes[value]} onChange={handleChange} />
{label}
</label>