Creating a dynamic form with conditional rendering in React involves using state to track the form's input values and conditions, as well as rendering different form fields based on certain conditions. Here's a basic example:
jsximport React, { useState } from 'react';
const DynamicForm = () => {
const [formData, setFormData] = useState({
firstName: '',
lastName: '',
isEmployed: false,
jobTitle: '',
});
const handleChange = (e) => {
const { name, value, type, checked } = e.target;
setFormData(prevState => ({
...prevState,
[name]: type === 'checkbox' ? checked : value
}));
};
return (
<form>
<label>
First Name:
<input
type="text"
name="firstName"
value={formData.firstName}
onChange={handleChange}
/>
</label>
<label>
Last Name:
<input
type="text"
name="lastName"
value={formData.lastName}
onChange={handleChange}
/>
</label>
<label>
Employed:
<input
type="checkbox"
name="isEmployed"
checked={formData.isEmployed}
onChange={handleChange}
/>
</label>
{formData.isEmployed && (
<label>
Job Title:
<input
type="text"
name="jobTitle"
value={formData.jobTitle}
onChange={handleChange}
/>
</label>
)}
<button type="submit">Submit</button>
</form>
);
};
export default DynamicForm;
In this example, the form contains fields for first name, last name, an employment status checkbox, and a job title input field. The job title field is conditionally rendered based on the value of the isEmployed
state. When the checkbox is checked, the job title field appears; otherwise, it's hidden.
This demonstrates how you can create a dynamic form with conditional rendering in React. Depending on your specific requirements, you can extend this pattern to include more complex conditions and form fields.