Forms
Uncontrolled Forms
In an uncontrolled form, we let the browser handle the form's state and rendering. We only react when the form is submitted using an onSubmit event handler.
Set up the HTML form as usual with the appropriate attributes (
name,value, etc.).Add an
onSubmitevent handler.Use
FormDatato get the form values.
const UncontrolledForm = () => {
const handleSubmit = (event) => {
event.preventDefault();
const formData = new FormData(event.target);
const fields = Object.fromEntries(formData);
console.log(fields);
// axios.post("/", fields);
};
return (
<form onSubmit={handleSubmit}>
<h1>Uncontrolled Form</h1>
<input type="text" name="name" placeholder="Name" />
<input type="email" name="email" placeholder="Email" />
<textarea name="comment" placeholder="Comment"></textarea>
<input type="submit" />
</form>
);
};Controlled Forms
In a controlled form, we wire up React to handle the form fields' states and rendering. This is typically used for cases where we need live access to the form values as the user enters data such as live form validation.
Controlled forms require a bit more setup than uncontrolled forms because state will be updated every time a form field changes (through keystrokes, clicks, etc.).
Create a state object with each form field's
nameas a property.Add an
onChangeon each form field that will update the state with its new value.Add a
valueprop to each form field and assign the corresponding state value.Add an
onSubmitevent on the form and use the state object to get the form values.
Live Password Confirmation Validation
Last updated
Was this helpful?