Handling Forms in React: Forms are essential for collecting user input. React provides controlled and uncontrolled components to manage form data.
- Controlled Components: The form data is handled by the component’s state. This approach allows React to control the form elements, making it easy to manage and validate input.
Example of a Controlled Component:
class MyForm extends React.Component {
constructor(props) {
super(props);
this.state = { name: '' };
}
handleChange = (event) => {
this.setState({ name: event.target.value });
};
handleSubmit = (event) => {
alert('A name was submitted: ' + this.state.name);
event.preventDefault();
};
render() {
return (
<form onSubmit={this.handleSubmit}>
<label>
Name:
<input type="text" value={this.state.name} onChange={this.handleChange} />
</label>
<button type="submit">Submit</button>
</form>
);
}
}
- Uncontrolled Components: The form data is handled by the DOM instead of React. This approach can be useful for quick prototyping or when you need to integrate with non-React libraries.
Example of an Uncontrolled Component:
class MyForm extends React.Component {
constructor(props) {
super(props);
this.inputRef = React.createRef();
}
handleSubmit = (event) => {
alert('A name was submitted: ' + this.inputRef.current.value);
event.preventDefault();
};
render() {
return (
<form onSubmit={this.handleSubmit}>
<label>
Name:
<input type="text" ref={this.inputRef} />
</label>
<button type="submit">Submit</button>
</form>
);
}
}