-
Form elements such as
<input>
,<textarea>
, and<select>
naturally keep some internal state (and change based on user's input). For example, this -
In React, mutable state is typically kept in the state of components. And when that state needs to change, we go through React (ie. we tell React to update state)
-
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, a controlled component is a component where we have a form + we store the state of the fields in React 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)
3.1. Create a stateful variable (for each field)
const [title, setTitle] = useState("");
3.2. Read the input value from state
<input ..... value={title} />
3.3 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(""); }