-
Form elements such as
<input>
,<textarea>
, and<select>
naturally keep some internal state (and change based on user's input). -
From the React team:
In most cases, we recommend using controlled components to implement forms. In a controlled component, form data is handled by a React component.
-
In short: when you work with froms, you usually want to store the info from the form in "State".
-
Create the form in your JSX:
<form> <input type="text" name="title" placeholder="enter the title" /> <button>Create</button> </form>
-
Add an
onSubmit
event & prevent form submission:const handleSubmit = (e) => { e.preventDefault(); }
<form onSubmit={handleSubmit}>
-
Make it a "Controlled Component" (we will store the data in state + read the data from state)
-
Create a stateful variable (for each field)
const [title, setTitle] = useState("");
-
Read the input value from state
<input ..... value={title} />
-
Add onChange event (and update state with the new value)
<input ..... onChange={(e) => { setTitle(e.target.value) }} />
-
-
Handle form submission
const handleSubmit = (e) => { e.preventDefault(); // //this is where your magic happens // }
-
(optional) clear form upon submission
const handleSubmit = (e) => { e.preventDefault(); // //this is where your magic happens // //clear form setTitle(""); }
For forms with a lot of fields....
Main ideas:
e.target.name
to access object properties dynamically).