React Forms Tutorial
In this tutorial, you will learn what are the forms and how to render them in React.
What are React Forms?
- React forms are essential for gathering and processing user input.
- In React, forms are created using HTML form elements and managed using state.
- To create a React form, you need to use the <form> element. You can then add input fields, text areas, and other form elements to the form.
const Form = () => {
const [name, setName] = useState('');
const [email, setEmail] = useState('');
const handleSubmit = (event) => {
event.preventDefault();
// Submit the form data to a server
};
return (
<form onSubmit={handleSubmit}>
<input
type="text"
name="name"
placeholder="Your name"
value={name}
onChange={(event) => setName(event.target.value)}
/>
<input
type="email"
name="email"
placeholder="Your email"
value={email}
onChange={(event) => setEmail(event.target.value)}
/>
<button type="submit">Submit </button>
</form>
);
};
Controlled vs. Uncontrolled Components in React
- In React, forms can be controlled or uncontrolled.
- Controlled components are React components where the form data is controlled by React state.
- Uncontrolled components rely on the DOM to store and manage form data.
<input
type="text"
value={this.state.inputValue}
onChange={this.handleChange}
/>
Handling Form Submissions
- To handle form submissions, you can use the onSubmit event handler on the <form> element.
- Use e.preventDefault() to prevent the default form submission behavior.
handleSubmit = (e) => {
e.preventDefault();
// Process form data and submit
}
Conditional Rendering
- Conditional rendering allows you to show/hide form elements based on user interactions or state.
- Use the render() method to conditionally display form elements.
{this.state.showAdditionalField && (
<input
type="text"
value={this.state.additionalValue}
onChange={this.handleAdditionalChange}
/>
)}
Form Libraries
- For complex forms, consider using form libraries like Formik or React Hook Form.
- These libraries simplify form handling and validation.
import { Formik, Form, Field, ErrorMessage } from 'formik';
<Formik
initialValues={{ name: '', email: '' }}
onSubmit={values => {
// Handle form submission
}}
>
<Form>
<Field type="text" name="name" />
<ErrorMessage name="name" component="div" />
<Field type="email" name="email" />
<ErrorMessage name="email" component="div" />
<button type="submit">Submit</button>
</Form>
</Formik>