27
loading...
This website collects cookies to deliver better user experience
state
variable and is updated with setState()
. But, using these methods together, is what brings us to that glorious single source of truth. When we tie the value of the element form to the state controlled by React, we form a controlled component. A controlled component derives its input values from state.<input />
, <select />
, and <textarea />
when we pass it a value prop of the current state.import React, { useState } from "react";
function myControlledForm() {
const [name, setName] = useState("");
const [favoriteColor, setFavoriteColor] = useState("");
return (
<form>
<input type="text" value={name} />
<input type="text" value={favoriteColor} />
<button type="submit">Submit</button>
</form>
);
}
export default Form;
name
and it's setter function setName
. It has an initial state declared as an empty string, but which will be updated as soon as, and every time setName
is called. onChange
event listener to an event handler callback function.<input type="text" onChange={handleNameChange} value={firstName} />
<input type="text" onChange={handleColorChange} value={lastName} />
function handleNameChange(event) {
setFirstName(event.target.value);
}
function handleColorChange(event) {
setLastName(event.target.value);
}
event.target.value
, which is being provided by the inputs onChange
event handler to update the state
variable using its corresponding setState
function, which we declared above. When we update the state, we cause a re-render, and a cycle is completed. onChange
and a callback, we can use these search values derived from state in a more scalable, expansive application to search and filter through all sorts of data.