Complex ReactJS form with different input forms and display on webpage
In this example, we'll have text inputs, a textarea, radio buttons, a checkbox, and a dropdown/select field. The submitted data will appear on the webpage. Remember, this is just a basic example, and you can change it to fit your needs.
import React, { useState } from 'react';
const ComplexForm = () => {
const [formData, setFormData] = useState({
firstName: '',
lastName: '',
email: '',
password: '',
bio: '',
gender: '',
agreeTerms: false,
country: 'Select Country'
});
const handleInputChange = (event) => {
const { name, value, type, checked } = event.target;
setFormData((prevData) => ({
...prevData,
[name]: type === 'checkbox' ? checked : value
}));
};
const handleSubmit = (event) => {
event.preventDefault();
// Access form data from formData state
console.log(formData);
// Perform form submission action (e.g., send data to server)
};
return (
<div>
<form onSubmit={handleSubmit}>
<label>
First Name:
<input
type="text"
name="firstName"
value={formData.firstName}
onChange={handleInputChange}
/>
</label>
<label>
Last Name:
<input
type="text"
name="lastName"
value={formData.lastName}
onChange={handleInputChange}
/>
</label>
<label>
Email:
<input
type="email"
name="email"
value={formData.email}
onChange={handleInputChange}
/>
</label>
<label>
Password:
<input
type="password"
name="password"
value={formData.password}
onChange={handleInputChange}
/>
</label>
<label>
Bio:
<textarea
name="bio"
value={formData.bio}
onChange={handleInputChange}
/>
</label>
<label>
Gender:
<div>
<label>
<input
type="radio"
name="gender"
value="male"
checked={formData.gender === 'male'}
onChange={handleInputChange}
/>
Male
</label>
<label>
<input
type="radio"
name="gender"
value="female"
checked={formData.gender === 'female'}
onChange={handleInputChange}
/>
Female
</label>
</div>
</label>
<label>
Agree to Terms:
<input
type="checkbox"
name="agreeTerms"
checked={formData.agreeTerms}
onChange={handleInputChange}
/>
</label>
<label>
Country:
<select
name="country"
value={formData.country}
onChange={handleInputChange}
>
<option value="Select Country" disabled>
Select Country
</option>
<option value="USA">USA</option>
<option value="Canada">Canada</option>
<option value="UK">UK</option>
</select>
</label>
<button type="submit">Submit</button>
</form>
{/* Display submitted data */}
<div>
<h2>Submitted Data:</h2>
<p>First Name: {formData.firstName}</p>
<p>Last Name: {formData.lastName}</p>
<p>Email: {formData.email}</p>
<p>Password: {formData.password}</p>
<p>Bio: {formData.bio}</p>
<p>Gender: {formData.gender}</p>
<p>Agree to Terms: {formData.agreeTerms ? 'Yes' : 'No'}</p>
<p>Country: {formData.country}</p>
</div>
</div>
);
};
export default ComplexForm;
This example has different input fields and manages their changes. The submitted data shows up under the form for checking. Change it more to fit your needs.