In this tutorial, we will learn how to manage complex form inputs using React. We will be handling multiple form inputs, capturing, and managing data using state variables.
What you will learn:
Prerequisites:
In React, managing form inputs involves two major tasks:
React provides two ways to manage form inputs:
State variables are used to store the data captured from the input fields. When a user inputs data into the field, we save it in the state variable. This data is then used for processing or for sending it to the server.
Below are some code examples that demonstrate how to manage multiple form inputs.
import React, { useState } from 'react';
function Form() {
const [name, setName] = useState('');
const [email, setEmail] = useState('');
const handleSubmit = (e) => {
e.preventDefault();
console.log(`Name: ${name}, Email: ${email}`);
};
return (
<form onSubmit={handleSubmit}>
<label>
Name:
<input type="text" value={name} onChange={e => setName(e.target.value)} />
</label>
<label>
Email:
<input type="email" value={email} onChange={e => setEmail(e.target.value)} />
</label>
<input type="submit" value="Submit" />
</form>
);
}
export default Form;
In this example, we're using controlled components to capture and manage the user's input. The useState
hook is used to create state variables name
and email
which store the user's input.
The onChange
event handler updates the state variables with the user's input. The handleSubmit
function is used to handle the form submission.
import React, { useState } from 'react';
function Form() {
const [name, setName] = useState('');
const [email, setEmail] = useState('');
const handleSubmit = (e) => {
e.preventDefault();
if(name.trim() === '' || email.trim() === '') {
alert('All fields are required!');
} else {
console.log(`Name: ${name}, Email: ${email}`);
}
};
return (
// ...rest of the code
);
}
export default Form;
In this example, we've added basic validation to the form. If the user tries to submit the form without filling in all fields, an alert is shown.
In this tutorial, we've learned how to manage complex form inputs in React. We've learned how to capture user's input and manage it using state variables. We've also seen how to validate form inputs.
For further learning, explore form libraries like Formik or React Hook Form. These libraries provide more advanced features for managing complex forms.
Exercise 1: Create a form with three fields: Name, Email, and Password. Capture and manage the data from these fields.
Exercise 2: Add validation to the form. Ensure that all fields are filled and that the email is in the correct format.
Exercise 3: Add a "Show Password" checkbox to the form. When checked, it should reveal the password entered in the password field.
Tips for Further Practice: Try to create forms with different types of inputs like radio buttons, checkboxes, dropdowns, etc. Learn how to handle these types of inputs in React.