React Forms
Forms are a crucial component of modern web applications, enabling user interaction and the collection of information. Depending on the business needs and logic, forms can handle a variety of tasks such as user authentication, adding users, searching, filtering, booking, ordering, and more. They can include elements like text fields, buttons, checkboxes, radio buttons, and others.
Creating Form
- React provides a state-driven, reactive approach for building forms, where the component, rather than the DOM, typically manages the form state. In React, forms are commonly implemented using controlled components.
- There are two main types of form inputs in React:
2. Controlled component
Uncontrolled Form
Uncontrolled inputs are similar to traditional HTML form elements, where the DOM manages the form data. In this approach, the HTML elements maintain their own state, which updates when the input value changes. To create an uncontrolled component, you use a ref to retrieve form values directly from the DOM. This means you don't need to write an event handler for every state change; instead, you can access the input field values using the ref.
Example
In this example, the code captures the username and company name fields using an uncontrolled component.
import React, { Component } from 'react';
class App extends React.Component {
constructor(props) {
super(props);
this.handleSubmit = this.handleSubmit.bind(this);
this.emailInput = React.createRef();
this.phoneInput = React.createRef();
}
handleSubmit(event) {
alert(`You entered Email: ${this.emailInput.current.value} and Phone Number: ${this.phoneInput.current.value}`);
event.preventDefault();
}
render() {
return (
<form onSubmit={this.handl
Output
Running the above code will display the following screen.
After entering the data in the fields, you will see the message displayed on the screen below.
Controlled Form
- In HTML, form elements usually manage their own state and update it based on user input. In a controlled component, however, the form element's state is managed by the component instead of the DOM. The mutable state is stored in the component's state property and can only be updated using the `setState()` method.
- Controlled components use functions to handle data on every `onChange` event, instead of capturing the data just once (e.g., when the submit button is clicked). The data is then stored in the component's state and updated using the `setState()` method. This approach gives the component better control over the form elements and the data.
- A controlled component receives its current value via props and notifies changes through callbacks, such as an `onChange` event. The parent component "controls" these changes by handling the callback, managing its own state, and passing the updated values as props to the controlled component. It is often referred to as a "dumb component."
Example
import React, { Component } from 'react';
class App extends React.Component {
constructor(props) {
super(props);
this.state = { email: '', password: '' };
this.handleEmailChange = this.handleEmailChange.bind(this);
this.handlePasswordChange = this.handlePasswordChange.bind(this);
this.handleSubmit = this.handleSubmit.bind(this);
}
handleEmailChange(event) {
this.setState({ email: event.target.value });
}
handlePasswordChange(event) {
this.setState({ password: event.target.value });
}
handleSubmit(event) {
alert('You have successfully submitted: ' + this.state.email + ' and ' + this.state.password);
event.preventDefault();
}
render() {
return (
<form onSubmit={this.handleSubmit}>
<h1>Controlled Form with Email and Password</h1>
<label>
Email:
<input type="email" value={this.state.email} onChange={this.handleEmailChange} />
</label>
<br />
<label>
Password:
<input type="password" value={this.state.password} onChange={this.handlePasswordChange} />
</label>
<br />
<input type="submit" value="Submit" />
</form>
);
}
}
export default App;
Output
When you run the above code, the following screen will be displayed.
After entering the data in the fields, the message shown on the screen below will appear.
Handling Multiple Inputs in Controlled Component
To handle multiple controlled input elements, add a `name` attribute to each element. The handler function can then determine what action to take based on the value of `event.target.name`.
Example
import React, { Component } from 'react';
class App extends React.Component {
constructor(props) {
super(props);
this.state = {
name: '',
email: '',
agreeToTerms: false
};
this.handleInputChange = this.handleInputChange.bind(this);
}
handleInputChange(event) {
const target = event.target;
const value = target.type === 'checkbox' ? target.checked : target.value;
const name = target.name;
this.setState({
[name]: value
});
}
render() {
return (
<form>
<h1>Sign Up Form Example</h1>
<label>
Name:
<input
name="name"
type="text"
value={this.state.name}
onChange={this.handleInputChange} />
</label>
<br />
<label>
Email:
<input
name="email"
type="email"
value={this.state.email}
onChange={this.handleInputChange} />
</label>
<br />
<label>
Agree to Terms:
<input
name="agreeToTerms"
type="checkbox"
checked={this.state.agreeToTerms}
onChange={this.handleInputChange} />
</label>
<br />
<button type="submit">Submit</button>
</form>
);
}
}
export default App;