Form is a collection of html elements created to accept user input of some type.
Forms in React are broadly classified as controlled and uncontrolled forms. Lets understand them in detail.
In general, input, textarea, and select has their own states.
In order to control their states and keep only one source of truth across the component, react needs to control what happens on the form and also on the subsequent input.
An input form element whose value is controlled by React in this way is called a “controlled component”. And accordingly, an form whose elements are controlled by React, are called as "controlled form".
Please note that file element <input type=“file”/> is a uncontrolled element in react as its value is read-only.
Controlled Component
We will create a simple form, where we will take user name and email address and on submit, display on the screen.
Data Binding to Form Fields
To bind data, we use value property.
We also need to make sure every input tag has a corresponding closing tag.
A sample input box in JSX will look like:
<div className="form-control">
<label htmlFor="email">Email : </label>
<input
type="email"
id="email"
name="email"
value={person.email}
onChange={handleChange}
/>
</div>
OnChange event handler
We need to implement onChange event to capture the change in values. Without this, form will be non-editable as we have already set the value to the state!
//need onChange handler to make sure form is editable in React
const handleChange = (e) => {
const { name, value } = e.target;
setPerson({ ...person, [name]: value });
};
Form Submit
We will create a list of people who who's information is submitted.
In React, we can submit forms in 2 ways:
- Handle form's onSubmit event
- Handle submit activities by implementing button's onClick event
By default, when a form submits, browser submits the form and refreshes the page. We want to prevent that. To do that, we must include event.preventDefault() statement as first activity when form submits.
const handleSubmit = (event) => {
//preventDefault so browser wont refresh the page after submit
event.preventDefault();
return person.name && person.email
? (function () {
const newPerson = { ...person, id: new Date().getTime().toString() };
setPeople([...people, newPerson]);
setPerson({
name: "",
email: "",
id: "",
});
})()
: console.log("Something's wrong!");
};
The JS looks like:
const ControlledInputs = () => {
const [person, setPerson] = useState({
name: "",
email: "",
id: "",
});
const [people, setPeople] = useState([]);
//need onChange handler to make sure form is editable in React
const handleChange = (e) => {
const { name, value } = e.target;
setPerson({ ...person, [name]: value });
console.log(person);
};
const handleSubmit = (event) => {
//preventDefault so browser wont refresh the page after submit
event.preventDefault();
return person.name && person.email
? (function () {
const newPerson = { ...person, id: new Date().getTime().toString() };
console.log("newPerson", newPerson);
setPeople([...people, newPerson]);
setPerson({
name: "",
email: "",
id: "",
});
})()
: console.log("something's wrong!");
};
return (
<>
<div className="row">
<div className="col-md-3">
<article>
<form className="form" style={{ marginTop: "5%" }}>
<div className="form-control">
<label htmlFor="name">Name : </label>
<input
type="text"
id="name"
name="name"
value={person.name}
onChange={handleChange}
/>
</div>
<div className="form-control">
<label htmlFor="email">Email : </label>
<input
type="email"
id="email"
name="email"
value={person.email}
onChange={handleChange}
/>
</div>
<button type="submit" onClick={handleSubmit}>
Add person
</button>
</form>
{
<ul className="list-group">
<br />
<h4 className="display-4" style={{ marginLeft: "20%" }}>
List of users
</h4>
{people.length > 0 ? (
people.map(({ name, email }, index) => {
return (
<>
<li
key={index}
className="list-group-item"
style={{ marginLeft: "20%" }}
>
<p>{name}</p>
<p>{email}</p>
</li>
</>
);
})
) : (
<h6 style={{ marginLeft: "20%" }}>No users to display</h6>
)}
</ul>
}
</article>
</div>
</div>
</>
);
};
export default ControlledInputs;
Output
Adding Person details
Comments
Post a Comment