Forms in React.js
1. Controlled Components
In React, form inputs such as <input>
, <textarea>
, and <select>
can be controlled components, meaning that their values are derived from the React component's state. The input element is controlled by React, and any changes are handled through events such as onChange
.
Example of a Controlled Input:
class NameForm extends React.Component {
constructor(props) {
super(props);
this.state = { name: '' }; // Initial state
}
handleChange = (event) => {
this.setState({ name: event.target.value }); // Update state with input value
};
handleSubmit = (event) => {
alert('A name was submitted: ' + this.state.name);
event.preventDefault(); // Prevents default form submission behavior
};
render() {
return (
);
}
}
ReactDOM.render( , document.getElementById('root'));
In this example:
this.state.name
).handleChange
function updates the state every time the user types something.handleSubmit
function handles the form submission, alerting the current input value and preventing the default form behavior.
2. Handling Multiple Inputs
In a more complex form, you might want to manage multiple input fields. In such cases, you can store all the input values in the component’s state as an object.
Example of Handling Multiple Inputs:
class ReservationForm extends React.Component {
constructor(props) {
super(props);
this.state = {
isGoing: true,
numberOfGuests: 2
};
}
handleInputChange = (event) => {
const { name, value, type, checked } = event.target;
const inputValue = type === 'checkbox' ? checked : value;
this.setState({
[name]: inputValue
});
};
render() {
return (
);
}
}
ReactDOM.render( , document.getElementById('root'));
In this example:
handleInputChange
is used for both the checkbox and number input.name
attribute of the input elements is used to update the corresponding state properties.isGoing
(a boolean) and numberOfGuests
(a number).
3. Handling Form Submission
When a form is submitted in React, you can control what happens using the onSubmit
event handler. The form is prevented from its default submission behavior using event.preventDefault()
.
Example:
handleSubmit = (event) => {
event.preventDefault(); // Prevents default form submission
// Custom form submission logic
};
When used inside a form element, this handler allows you to submit data programmatically or perform other actions (e.g., validation, API calls).
4. Form Validation
Form validation is crucial to ensure data integrity before submission. In React, you can implement validation by checking the form state during or after input.
Example of Basic Validation:
class FormWithValidation extends React.Component {
constructor(props) {
super(props);
this.state = {
username: '',
errorMessage: ''
};
}
handleChange = (event) => {
const value = event.target.value;
this.setState({ username: value });
if (value.length < 5) {
this.setState({ errorMessage: 'Username must be at least 5 characters long.' });
} else {
this.setState({ errorMessage: '' });
}
};
handleSubmit = (event) => {
event.preventDefault();
if (this.state.errorMessage === '') {
alert('Form submitted successfully!');
}
};
render() {
return (
);
}
}
ReactDOM.render( , document.getElementById('root'));
In this example:
username
) and any error messages.errorMessage
is displayed in case of invalid input
Conclusion
Forms in React are primarily managed using controlled components, where form inputs derive their values from the component's state. React also provides flexibility for handling multiple inputs, validating user input, and submitting data efficiently. While uncontrolled components offer a simpler approach for basic forms, controlled components are generally recommended for better consistency, validation, and dynamic behavior. Understanding how to handle forms in React is key to building interactive user interfaces.