Introduction
Welcome to Day 9 of our 30-day blog series on React.js! Today, we'll dive into forms in React and explore how to handle user input and form submission effectively. Forms are an essential part of web applications, allowing users to input and submit data.
Controlled Components
In React, form elements such as input, textarea, and select maintain their state in the component's state. Components that render form elements and control their state are called controlled components.
class LoginForm extends React.Component {
constructor(props) {
super(props);
this.state = { username: '', password: '' };
}
handleChange = event => {
this.setState({ [event.target.name]: event.target.value });
};
handleSubmit = event => {
event.preventDefault();
// Handle form submission
console.log('Form submitted:', this.state);
};
render() {
return (
<form onSubmit={this.handleSubmit}>
<input
type="text"
name="username"
value={this.state.username}
onChange={this.handleChange}
placeholder="Username"
/>
<input
type="password"
name="password"
value={this.state.password}
onChange={this.handleChange}
placeholder="Password"
/>
<button type="submit">Submit</button>
</form>
);
}
}
In the above example:
The
LoginForm
component contains two controlled input elements for username and password.The
handleChange
method updates the component's state as the user types into the input fields.The
handleSubmit
method handles the form submission and prevents the default behavior.
Uncontrolled Components
In addition to controlled components, React also supports uncontrolled components, where the form data is handled by the DOM itself rather than React state. Uncontrolled components are typically used when integrating React with non-React code or working with third-party libraries.
function UncontrolledForm() {
const handleSubmit = event => {
event.preventDefault();
const formData = new FormData(event.target);
console.log('Form submitted:', {
username: formData.get('username'),
password: formData.get('password'),
});
};
return (
<form onSubmit={handleSubmit}>
<input type="text" name="username" placeholder="Username" />
<input type="password" name="password" placeholder="Password" />
<button type="submit">Submit</button>
</form>
);
}
In the above example, the form submission is handled by accessing form data directly from the event target.
Forms are a crucial part of web development, and React provides powerful tools for handling user input and form submission. Whether using controlled components for managing form state within React components or uncontrolled components for integrating with external libraries, understanding how to work with forms effectively is essential for building interactive React applications.
Stay tuned for tomorrow's post, where we'll explore lifecycle methods in React and how to perform actions at different stages of a component's lifecycle.