ReactJs Tutorials
How to create React Forms?
Forms allows the users to interact with the application as well as gather information from the users.
Forms perform many tasks such as submitting the data, searching, filtering etc. A form can contain text fields, buttons, checkbox, radio button, selectbox etc.
In HTML, form data is handled by the DOM. but in React, form data is handled by the components. When the data is handled by the components, all the data is stored in the component state.
How to creating a form in react?
There are two types of form input in React.
File name : index.php
Controlled component
Uncontrolled component
We can use the useState Hook to keep track of each inputs value and provide a "single source of truth" for the entire application.
Example
File name :
import { useState } from "react";
import ReactDOM from 'react-dom';
function MyForm() {
const [name, setName] = useState("");
return (
<form>
<label>Enter your name:
<input
type="text"
value={name}
onChange={(e) => setName(e.target.value)}
/>
</label>
</form>
)
}
ReactDOM.render(<MyForm />, document.getElementById('root'));
Submitting Forms
File name :
import { useState } from "react";
import ReactDOM from 'react-dom';
function MyForm() {
const [name, setName] = useState("");
const handleSubmit = (event) => {
event.preventDefault();
alert(`The name you entered was: ${name}`);
}
return (
<form onSubmit={handleSubmit}>
<label>Enter your name:
<input
type="text"
value={name}
onChange={(e) => setName(e.target.value)}
/>
</label>
<input type="submit" />
</form>
)
}
ReactDOM.render(<MyForm />, document.getElementById('root'));
Multiple Input Fields
File name :
import { useState } from "react";
import ReactDOM from "react-dom";
function MyForm() {
const [inputs, setInputs] = useState({});
const handleChange = (event) => {
const name = event.target.name;
const value = event.target.value;
setInputs(values => ({...values, [name]: value}))
}
const handleSubmit = (event) => {
event.preventDefault();
console.log(inputs);
}
return (
<form onSubmit={handleSubmit}>
<label>Enter your name:
<input
type="text"
name="username"
value={inputs.username || ""}
onChange={handleChange}
/>
</label>
<label>Enter your age:
<input
type="number"
name="age"
value={inputs.age || ""}
onChange={handleChange}
/>
</label>
<input type="submit" />
</form>
)
}
ReactDOM.render(<MyForm />, document.getElementById('root'));
Textarea
File name :
import { useState } from "react";
import ReactDOM from "react-dom";
function MyForm() {
const [textarea, setTextarea] = useState(
"The content of a textarea goes in the value attribute"
);
const handleChange = (event) => {
setTextarea(event.target.value)
}
return (
<form>
<textarea value={textarea} onChange={handleChange} />
</form>
)
}
ReactDOM.render(<MyForm />, document.getElementById('root'));
Select
File name :
import { useState } from "react";
import ReactDOM from "react-dom";
function MyForm() {
const [myCar, setMyCar] = useState("Volvo");
const handleChange = (event) => {
setMyCar(event.target.value)
}
return (
<form>
<select value={myCar} onChange={handleChange}>
<option value="Ford">Ford</option>
<option value="Maruti">maruti</option>
<option value="Hundai">Hundai</option>
</select>
</form>
)
}
ReactDOM.render(<MyForm />, document.getElementById('root'));
Uncontrolled component :-
File name :
import React, { Component } from 'react';
class App extends React.Component {
constructor(props) {
super(props);
this.updateSubmit = this.updateSubmit.bind(this);
this.input = React.createRef();
}
updateSubmit(event) {
alert('You have entered the UserName and CompanyName successfully.');
event.preventDefault();
}
render() {
return (
<form onSubmit={this.updateSubmit}>
<h1>Uncontrolled Form Example</h1>
<label>Name:
<input type="text" ref={this.input} />
</label>
<label>
CompanyName:
<input type="text" ref={this.input} />
</label>
<input type="submit" value="Submit" />
</form>
);
}
}
export default App;
Controlled Component
File name :
import React, { Component } from 'react';
class App extends React.Component {
constructor(props) {
super(props);
this.state = {value: ''};
this.handleChange = this.handleChange.bind(this);
this.handleSubmit = this.handleSubmit.bind(this);
}
handleChange(event) {
this.setState({value: event.target.value});
}
handleSubmit(event) {
alert('You have submitted the input successfully: ' + this.state.value);
event.preventDefault();
}
render() {
return (
<form onSubmit={this.handleSubmit}>
<h1>Controlled Form Example</h1>
<label>
Name:
<input type="text" value={this.state.value} onChange={this.handleChange} />
</label>
<input type="submit" value="Submit" />
</form>
);
}
}
export default App;
Handling Multiple Inputs in Controlled Component
File name :
import React, { Component } from 'react';
class App extends React.Component {
constructor(props) {
super(props);
this.state = {
personGoing: true,
numberOfPersons: 5
};
this.handleInputChange = this.handleInputChange.bind(this);
}
handleInputChange(event) {
const target = event.target;
const value = target.type === 'checkbox' ? target.checked : target.value;
const name = target.name;
this.setState({
[name]: value
});
}
render() {
return (
<form>
<h1>Multiple Input Controlled Form Example</h1>
<label>
Is Person going:
<input
name="personGoing"
type="checkbox"
checked={this.state.personGoing}
onChange={this.handleInputChange} />
</label>
<br />
<label>
Number of persons:
<input
name="numberOfPersons"
type="number"
value={this.state.numberOfPersons}
onChange={this.handleInputChange} />
</label>
</form>
);
}
}
export default App;
Example Of Form in React.
File name : ExpenseForm
import React from 'react';
import './ExpenseForm.css'
class ExpenseForm extends React.Component {
constructor(props) {
super(props);
this.state = {
item: {}
}
this.handleNameChange = this.handleNameChange.bind(this);
this.handleAmountChange = this.handleAmountChange.bind(this);
this.handleDateChange = this.handleDateChange.bind(this);
this.handleCategoryChange = this.handleCategoryChange.bind(this);
}
handleNameChange(e) {
this.setState( (state, props) => {
let item = state.item
item.name = e.target.value;
return { item: item }
});
}
handleAmountChange(e) {
this.setState( (state, props) => {
let item = state.item
item.amount = e.target.value;
return { item: item }
});
}
handleDateChange(e) {
this.setState( (state, props) => {
let item = state.item
item.date = e.target.value;
return { item: item }
});
}
handleCategoryChange(e) {
this.setState( (state, props) => {
let item = state.item
item.category = e.target.value;
return { item: item }
});
}
onSubmit = (e) => {
e.preventDefault();
alert(JSON.stringify(this.state.item));
}
render() {
return (
<div id="expenseForm">
<form onSubmit={(e) => this.onSubmit(e)}>
<label for="name">Title</label>
<input type="text" id="name" name="name" placeholder="Enter expense title"
value={this.state.item.name}
onChange={this.handleNameChange} />
<label for="amount">Amount</label>
<input type="number" id="amount" name="amount" placeholder="Enter expense amount"
value={this.state.item.amount}
onChange={this.handleAmountChange} />
<label for="date">Spend Date</label>
<input type="date" id="date" name="date" placeholder="Enter date"
value={this.state.item.date}
onChange={this.handleDateChange} />
<label for="category">Category</label>
<select id="category" name="category"
value={this.state.item.category}
onChange={this.handleCategoryChange} >
<option value="">Select</option>
<option value="Food">Food</option>
<option value="Entertainment">Entertainment</option>
<option value="Academic">Academic</option>
</select>
<input type="submit" value="Submit" />
</form>
</div>
)
}
}
export default ExpenseForm;
File name : ExpenseForm.css
input[type=text], input[type=number], input[type=date], select {
width: 100%;
padding: 12px 20px;
margin: 8px 0;
display: inline-block;
border: 1px solid #ccc;
border-radius: 4px;
box-sizing: border-box;
}
input[type=submit] {
width: 100%;
background-color: #4CAF50;
color: white;
padding: 14px 20px;
margin: 8px 0;
border: none;
border-radius: 4px;
cursor: pointer;
}
input[type=submit]:hover {
background-color: #45a049;
}
input:focus {
border: 1px solid #d9d5e0;
}
#expenseForm div {
border-radius: 5px;
background-color: #f2f2f2;
padding: 20px;
}
File name : index.js
import React from 'react';
import ReactDOM from 'react-dom';
import ExpenseForm from './components/ExpenseForm'
ReactDOM.render(
<React.StrictMode>
<ExpenseForm />
</React.StrictMode>,
document.getElementById('root')
);
File name : index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>React App</title>
</head>
<body>
<div id="root"></div>
<script type="text/JavaScript" src="./index.js"></script>
</body>
</html>
Create Form Input
Create a form element.
<input type="text" name="username" />
Create a state for input element.
this.state = {
username: ''
}
Add a value attribute and assign the value from state.
<input type="text" name="username" value={this.state.username} />
Add a onChange attribute and assign a handler method.
<input type="text" name="username" value={this.state.username} onChange={this.handleUsernameChange} />
Write the handler method and update the state whenever the event is fired.
handleUsernameChange(e) {
this.setState({
username = e.target.value
});
}
Bind the event handler in the constructor of the component.
this.handleUsernameChange = this.handleUsernameChange.bind(this)
Finally, get the input value using username from this.state during validation and submission.
handleSubmit(e) {
e.preventDefault();
alert(this.state.username);
}
Uncontrolled Component :-
uncontrolled component does not support React based form programming. Getting a value of a React DOM element (form element) is not possible without using React api. One way to get the content of the react component is using React ref feature.
React provides a ref attribute for all its DOM element and a corresponding api, React.createRef() to create a new reference (this.ref). The newly created reference can be attached to the form element and the attached form element’s value can be accessed using this.ref.current.value whenever necessary (during validation and submission).
Create a reference.
this.inputRef = React.createRef();
Create a form element.
<input type="text" name="username" />
Attach the already created reference in the form element.
<input type="text" name="username" ref={this.inputRef} />
To set defalut value of an input element, use defaultValue attribute instead of value attribute. If value is used, it will get updated during rendering phase of the component.
<input type="text" name="username" ref={this.inputRef} defaultValue="default value" />
Finally, get the input value using this.inputRef.current.value during validation and submission.
handleSubmit(e) {
e.preventDefault();
alert(this.inputRef.current.value);
}
Example
import React from 'react';
import './ExpenseForm.css'
class ExpenseForm extends React.Component {
constructor(props) {
super(props);
this.nameInputRef = React.createRef();
this.amountInputRef = React.createRef();
this.dateInputRef = React.createRef();
this.categoryInputRef = React.createRef();
}
onSubmit = (e) => {
e.preventDefault();
let item = {};
item.name = this.nameInputRef.current.value;
item.amount = this.amountInputRef.current.value;
item.date = this.dateInputRef.current.value;
item.category = this.categoryInputRef.current.value;
alert(JSON.stringify(item));
}
render() {
return (
<div id="expenseForm">
<form onSubmit={(e) => this.onSubmit(e)}>
<label for="name">Title</label>
<input type="text" id="name" name="name" placeholder="Enter expense title"
ref={this.nameInputRef} />
<label for="amount">Amount</label>
<input type="number" id="amount" name="amount" placeholder="Enter expense amount"
ref={this.amountInputRef} />
<label for="date">Spend Date</label>
<input type="date" id="date" name="date" placeholder="Enter date"
ref={this.dateInputRef} />
<label for="category">Category</label>
<select id="category" name="category"
ref={this.categoryInputRef} >
<option value="">Select</option>
<option value="Food">Food</option>
<option value="Entertainment">Entertainment</option>
<option value="Academic">Academic</option>
</select>
<input type="submit" value="Submit" />
</form>
</div>
)
}
}
export default ExpenseForm;
index.js
import React from 'react';
import ReactDOM from 'react-dom';
import ExpenseForm from './components/ExpenseForm'
ReactDOM.render(
<React.StrictMode>
<ExpenseForm />
</React.StrictMode>,
document.getElementById('root')
);