We will be using state to make a controlled form React. The form wants to get the first name, age, and location of a user. The first thing we need to do is import state to the component and set up the form.
import React, {useState} from "react";
function form (){
const [formValues, setFormValues] = useState({
firstName: "",
age: 0,
location: ""
})
return(
<form>
<input name="firstName" />
<input name="age" />
<input name="location" />
<button type="submit">Submit</button>
</form>
)
}
From the code above, we will be collection all he input in one state. Now that everything is set up we can move forward. We need to write a function that can handle changes to the form inputs and set the values in the state.
import React, {useState} from "react";
function form (){
const [formValues, setFormValues] = useState({
firstName: "",
age: 0,
location: ""
})
const handleChange = (e) => {
setFormValues({...formValues, [e.target.name]:e.target.value})
}
return(
<form>
<input
name="firstName"
value={formValues.firstName}
onChange={handleChange}
/>
<input
name="age"
value={formValues.age}
onChange={handleChange}
/>
<input
name="location"
value={formValues.location}
onChange={handleChange}
/>
<button type="submit">Submit</button>
</form>
)
}
In the code above, you can see that the handleChange function uses the spread operator on the initial state structure. It then uses [e.target.name], by placing this in square brackets, the e.target.name becomes more flexible. This will then associate name value that is respective input. The handleChange also sets the state to an object withe the respective key:value pairs.
The next step is to submit the form and post it to the database.
import React, {useState, useEffect} from "react";
function form (){
const [formValues, setFormValues] = useState({
firstName: "",
age: 0,
location: ""
})
const handleChange = (e) => {
setFormValues({...formValues, [e.target.name]: e.target.value})
}
const handleSubmit = (e) => {
e.preventDefault()
fetch('SOME API HERE', {
method: 'POST',
headers: {'Content-Type': 'application/json'},
body: JSON.stringify(formValues)
})
}
return(
<form onSubmit={handleSubmit} >
<input
name="firstName"
value={formValues.firstName}
onChange={handleChange}
/>
<input
name="age"
value={formValues.age}
onChange={handleChange}
/>
<input
name="location"
value={formValues.location}
onChange={handleChange}
/>
<button type="submit">Submit</button>
</form>
)
}
Top comments (0)