In React, handling forms involves using the <form>
tag and managing the form’s state. Here’s a simple example of using a form in a React component:
import React, { useState } from 'react';
const MyForm = () => {
// State to manage form data
const [formData, setFormData] = useState({
username: '',
email: '',
});
// Function to handle form input changes
const handleInputChange = (e) => {
const { name, value } = e.target;
setFormData({ ...formData, [name]: value });
};
// Function to handle form submission
const handleSubmit = (e) => {
e.preventDefault();
// Perform actions with form data (e.g., send data to server)
console.log('Form data submitted:', formData);
};
return (
<form onSubmit={handleSubmit}>
{/* Input for username */}
<label>
Username:
<input
type="text"
name="username"
value={formData.username}
onChange={handleInputChange}
/>
</label>
{/* Input for email */}
<label>
Email:
<input
type="email"
name="email"
value={formData.email}
onChange={handleInputChange}
/>
</label>
{/* Submit button */}
<button type="submit">Submit</button>
</form>
);
};
export default MyForm;
In this example:
- We use the
useState
hook to create a state variableformData
to manage the form data. The initial state includes fields forusername
andemail
. - The
handleInputChange
function is called whenever the user types into an input field. It updates the corresponding field in theformData
state. - The
handleSubmit
function is called when the form is submitted. It prevents the default form submission behavior, allowing you to handle the submission programmatically. In this example, it logs the form data to the console. - Each input field in the form has a corresponding
name
attribute, allowing you to update the specific field in theformData
state. - The
value
attribute of each input is set to the corresponding value in theformData
state, creating a controlled component.
Using this approach, you can easily extend and customize your form handling logic in React. Keep in mind that for more complex forms or for managing global form state, you might consider using form libraries like Formik or react-hook-form.
in HTML form tag is used to collect input data to send to the server. similarly in React form tag work.
form tag in React is used in Component through the render() method like other HTML tags that we want to render.
form tag collects data in the form of get or post which we define in the method to collect data to send to the server.
Example to use form tag in react Component?
class Fillname extends React.Component {
render() {
return (
<form>
<h1>Hi</h1>
<p>fill your name:</p>
<input
type="text"
/>
</form>
);
}
}
ReactDOM.render(<Fillname />, document.getElementById('root'));
when react will call the Filename component through the render() method of component form tag will appear in DOM with an input tag like what we use in the HTML form tag
Event handler of React form tag
Event handler of React form tag input we can handle similar to HTML attribute
in HTML DOM handle the form data while in React Component will handle the data
in React all form data is stored in an inbuilt Component object state
Example:
class Myname extends React.Component {
constructor(props) {
super(props);
this.state = { myname: '' };
}
myChangeHandler = (event) => {
this.setState({username: event.target.value});
}
render() {
return (
<form>
<h1>Hello {this.state.myname}</h1>
<p>Enter name:</p>
<input
type='text'
onChange={this.myChangeHandler}
/>
</form>
);
}
}
ReactDOM.render(<Myname />, document.getElementById('root'));
How to use conditions in React form tag?
if you want conditional programming then let’s take an example
class Myname extends React.Component {
constructor(props) {
super(props);
this.state = { name: '' };
}
myChangeHandler = (event) => {
this.setState({name: event.target.value});
}
render() {
let flag= '';
if (this.state.name) {
header = <h1>Hello {this.state.name}</h1>;
} else {
flag= '';
}
return (
<form>
{flag}
<p>Enter your name:</p>
<input
type='text'
onChange={this.myChangeHandler}
/>
</form>
);
}
}
ReactDOM.render(<Myname />, document.getElementById('root'));
in the above example, the flag variable is defined on behalf of conditional programming
if there is input the flag text will display in DOM otherwise not
Submit Event handler in React form tag?
Example of Submit Event Handler
class ReactForm extends React.Component {
constructor(props) {
super(props);
this.state = { name: '' };
}
mySubmitHandler = (event) => {
event.preventDefault();
alert("You are submitting " + this.state.name);
}
myChangeHandler = (event) => {
this.setState({name: event.target.value});
}
render() {
return (
<form onSubmit={this.mySubmitHandler}>
<h1>Hello {this.state.name}</h1>
<p>fill your name</p>
<input
type='text'
onChange={this.myChangeHandler}
/>
<input
type='submit'
/>
</form>
);
}
}
ReactDOM.render(<ReactForm />, document.getElementById('root'));
in the above Example preventDefault() Event cancel the event
How React handle multiple Input Fields
Multiple input with name attribute is used to set the state property of React component in the constructor through props.
in React square brackets [ ] is used to update the property name of the state property of React component if multiple inputs have.
class Reactform extends React.Component {
constructor(props) {
super(props);
this.state = {
username: '',
age: null,
};
}
myChangeHandler = (event) => {
let nam = event.target.name;
let val = event.target.value;
this.setState({[nam]: val});
}
render() {
return (
<form>
<h1>Output is {this.state.username} {this.state.age}</h1>
<p>Enter your name:</p>
<input
type='text'
name='username'
onChange={this.myChangeHandler}
/>
<p>Enter your age:</p>
<input
type='text'
name='age'
onChange={this.myChangeHandler}
/>
</form>
);
}
}
ReactDOM.render(<Reactform />, document.getElementById('root'));
in the above example, Square brackets [ ] behave like an array to update the state name.
first, it will update the username then the age of state property name
How does React validate form input fields?
React validate form input fields through Component. there will be no submission until the form gets validated
Example
class Reactform extends React.Component {
constructor(props) {
super(props);
this.state = {
username: '',
age: null,
};
}
myChangeHandler = (event) => {
let nam = event.target.name;
let val = event.target.value;
if (nam === "age") {
if (!Number(val)) {
alert("age should be number");
}
}
this.setState({[nam]: val});
}
render() {
return (
<form>
<h1>Hello {this.state.username} {this.state.age}</h1>
<p>Enter your name:</p>
<input
type='text'
name='username'
onChange={this.myChangeHandler}
/>
<p>Enter your age:</p>
<input
type='text'
name='age'
onChange={this.myChangeHandler}
/>
</form>
);
}
}
ReactDOM.render(<Reactform />, document.getElementById('root'));
Example of form validation after Form submission?
class Reactform extends React.Component {
constructor(props) {
super(props);
this.state = {
username: '',
age: null,
};
}
mySubmitHandler = (event) => {
event.preventDefault();
let age = this.state.age;
if (!Number(age)) {
alert("age must be a number");
}
}
myChangeHandler = (event) => {
let nam = event.target.name;
let val = event.target.value;
this.setState({[nam]: val});
}
render() {
return (
<form onSubmit={this.mySubmitHandler}>
<h1>Hello {this.state.username} {this.state.age}</h1>
<p>Enter your name:</p>
<input
type='text'
name='username'
onChange={this.myChangeHandler}
/>
<p>Enter your age:</p>
<input
type='text'
name='age'
onChange={this.myChangeHandler}
/>
<br/>
<br/>
<input type='submit' />
</form>
);
}
}
ReactDOM.render(<Reactform />, document.getElementById('root'));
Example of React form validation without Alert
class Reactform extends React.Component {
constructor(props) {
super(props);
this.state = {
username: '',
age: null,
errormessage: ''
};
}
myChangeHandler = (event) => {
let nam = event.target.name;
let val = event.target.value;
let err = '';
if (nam === "age") {
if (val !="" && !Number(val)) {
err = <strong>age must be a number</strong>;
}
}
this.setState({errormessage: err});
this.setState({[nam]: val});
}
render() {
return (
<form>
<h1>Hello {this.state.username} {this.state.age}</h1>
<p>Enter your name:</p>
<input
type='text'
name='username'
onChange={this.myChangeHandler}
/>
<p>Enter your age:</p>
<input
type='text'
name='age'
onChange={this.myChangeHandler}
/>
{this.state.errormessage}
</form>
);
}
}
ReactDOM.render(<Reactform />, document.getElementById('root'));
Example of textarea in ReactForm
class Textarea extends React.Component {
constructor(props) {
super(props);
this.state = {
description: 'text area'
};
}
render() {
return (
<form>
<textarea value={this.state.description} />
</form>
);
}
}
ReactDOM.render(<Textarea />, document.getElementById('root'));
Example of selection tag in React form
class Selection extends React.Component {
constructor(props) {
super(props);
this.state = {
name: 'yashpal'
};
}
render() {
return (
<form>
<select value={this.state.name}>
<option value="christo">christo</option>
<option value="killian">killian</option>
<option value="start lord">start lord</option>
</select>
</form>
);
}
}
ReactDOM.render(<Selection />, document.getElementById('root'));