Day-7 Building Forms in React JS
Creating and Implementing Form Validation and Submission
Creating Forms in ReactJS Creating a form in ReactJS is similar to creating a form in HTML, with some added functionality. You can use the <form>
tag to create a form in ReactJS, and within the form, you can use various input types, such as text fields, checkboxes, and radio buttons, to gather user input.
Example:
import React, { Component } from 'react';
class MyForm extends Component {
render() {
return (
<form>
<label>
Name:
<input type="text" name="name" />
</label>
<input type="submit" value="Submit" />
</form>
);
}
}
Handling Form Input In ReactJS, you can handle form input using the onChange
event. The onChange
event is fired whenever the user types something into an input field, allowing you to update the state of the form.
Example:
import React, { Component } from 'react';
class MyForm extends 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>
<input type="submit" value="Submit" />
</form>
);
}
}
Form Validation Form validation is an essential part of any web application, ensuring that the data submitted by the user is in the correct format. ReactJS provides an easy way to perform form validation using the onSubmit
event.
Example:
import React, { Component } from 'react';
class MyForm extends Component {
constructor(props) {
super(props);
this.state = { name: '', email: '' };
}
handleChange = (event) => {
this.setState({ [event.target.name]: event.target.value });
}
handleSubmit = (event) => {
if (!this.state.name || !this.state.email) {
alert('Please enter your name and email.');
event.preventDefault();
} else {
alert('A name and email was submitted: ' + this.state.name + ' ' + this.state.email);
event.preventDefault();
}
}
render() {
return (
<form onSubmit={this.handleSubmit}>
<label>
Name:
<input type="text" name="name" value={this.state.name} onChange={this.handleChange} />
</label>
<br />
<label>
Email:
<input type="text" name="email" value={this.state.email} onChange={this.handleChange} />
</label>
<br />
<input type="submit" value="Submit" />
</form>
);
}
}
Form Submission In ReactJS, you can submit form data using the onSubmit
event. When the user clicks the submit button, the onSubmit
event is fired, and you can access the form data