React Forms

React Forms: In this tutorial, You will learn to create and handle forms in React js with some examples & steps.

So, You must read all the given points carefully. because the concept of  React forms is a bit different from HTML forms.

Using react form, You can quickly handle simple & complex input data without refreshing the page. Even you can modify input data and display warning/success messages in real-time(While you start entering a value in the input field)

For example, If you need to convert input data in uppercase while the user starts entering data and also, display a warning message when the user enters invalid data. These all things can be easily implemented in react Js

Learn also –

Create Charts in React Js

How to Display Images in React Js

How to Use Bootstrap in React Js

React Event Handling

Forms in React Js

Now I am going to learn you a form from basic to advance. So that you can easily understand its working concept and quickly implement it in your project. So, Let’s start with the next step.

1. Create a Form

As you know that an HTML form contains many input fields like text, password, email, radio, checkbox, select, textarea & others. Even React also contains all these input fields but It is created in the form of JSX  then rendered to the DOM.

Here, I will show you how to create a form with a single text type input field. Once, you learn it, you can test yourself with multiple input fields.

File Name – App.js

import React from 'react';
function App() {
  return (
    <form>
        <input type="text" />
    </form>
  )
}
Export default App;

2. Handle a Form

In previous step no 1, We have just created just a form that is handled by the DOM. But It is not good for React Js, You will have to handle that form by a component.

Important Points –

  • When you handle a form using a component then you will have to store its data in the state.
  • In react Js, You can control form data using the onChange event.
  • If you create a form within a  functional component, then you will have to use the useState to update the state data
  • If you create a form within a class component, then you will have to use the setState() to update the state data.

Form within a  functional component

File Name – App.js

import React from 'react';
function App() {
const [fullName, setFullName] = useState("");
handleChange = (event) => {
 setFullName(event.target.value)
}
  return (
    <form>
        <input type="text"  value={fullName} onChange={handleChange} />
    </form>
  )
}
Export default App;

Form within a  class component

import React from 'react';
class App extends from React.Component {
state = {
  fullName:""
}
let handleChange = (event) => {
  this.setState({fullName:event.target.value})
}
render(){
  return (
    <form onSubmit={handleSubmit}>
        <input type="text"  value={this.state.fullName} onChange={this.handleChange} />
    </form>
  )
}
}
Export default App;

 

3. Submit a Form

If you submit the normal HTML form then It will refresh. But you can handle it using the event handler and prevent it from refreshing/reloading.

Important Point –

  • You can use <input type=”submit>  or <button></button> tag to submit the form
  • You can use the onSubmit event within the <form> tag to handle the default behavior of the submit form.

File Name – App.js

import React from 'react';
function App() {
const [fullName, setFullName] = useState("");
let handleChange = (event) => {
 setFullName(event.target.value)
}
 let handleSubmit = (event) => {
    event.preventDefault();
}

  return (
    <form onSubmit={handleSubmit}>
        <input type="text"  value={fullName} onChange={handleChange} />
        <input type="submit" />
    </form>
  )
}
Export default App;

Controlled Component

The value of a form input field is controlled by React Js is called Controlled Component.

Not controlled by React 

If you need to use the value attribute to display the default/existing value in the input field (It is mostly implemented to edit/update data). then you will get a warning error in the browser console if the input value is not controlled by React.

Example –

import React from 'react';
function App() {
  return (
    <form>
        <input type="text" value="Noor Khan" />
    </form>
  )
}
Export default App;

When you run the above code, you will get an input field with the default value “Noor khan”. This input value will not be changed/updated and also you will get a warning in the browser console. So, to resolve it, you will learn in the next step.

Controlled by React

The warning error of the previous step can be resolved if the input value is controlled by React.

The input value can be controlled by React using the following ways –

  • Event Hander
  • defaultAttribute

Using Event Hander

If you need to handle input value then you can use the Event Handler

import React from 'react';
function App() {
const [fullName, setFullName] = useState("");
handleChange = (event) => {
 setFullName(event.target.value)
}
  return (
    <form>
        <input type="text"  value={fullName} onChange={handleChange} />
    </form>
  )
}
Export default App;

Using defaultValue

If you need not handle input value then you can use the defaultValue attribute

import React from 'react';
function App() {
  return (
    <form>
        <input type="text" defaultValue="Noor Khan" />
    </form>
  )
}
Export default App;

Usage –

If you need to modify the input value then you can also do it using JavaScript. But It may be very difficult to handle large input data. So, You have a standard way to implement it using the Controlled Component.

Example –

When the user starts to enter data in lowercase or uppercase into the input field, data should be updated in uppercase.

import React from 'react';
function App() {
const [fullName, setFullName] = useState("");
handleChange = (event) => {
 setFullName(event.target.value.toUpperCase())
}
  return (
    <form>
        <input type="text"  value={fullName} onChange={handleChange} />
    </form>
  )
}
Export default App;

Important Points –

  • Whenever you need the modification in the value of an input filed then you should use the Controlled component
  • To use a controlled component, You should specify an initial input value and use the event handler.

To better understand the concept of controlled component, We will learn to implement more useful form input fields one by one from the next steps

Text Input Field

In react,  You should create a text input field with a value attribute and handle them using an event handler.

Example –

import React from 'react';
function App() {
const [fullName, setFullName] = useState("");
handleChange = (event) => {
 setFullName(event.target.value)
}
  return (
    <form>
        <input type="text"  value={fullName} onChange={handleChange} />
    </form>
  )
}
Export default App;

Note – You can create other input fields (such as password, email, radio & check box ) similar to the text input field

Textarea Input Field

In HTML, default value of a textarea input field is put between <textarea></textare> But in react js, you will have to declare value attribute within <textarea> to put default value and handle it using the Event Handler.

import React from 'react';
function App() {
const [fullName, setFullName] = useState("My Noor Name is Khan From Bihar India");
handleChange = (event) => {
 setFullName(event.target.value)
}
  return (
    <form>
        <textarea type="text"  value={fullName} onChange={handleChange} />
    </form>
  )
}
Export default App;

Select Input Field

In react,  You should create a select input field with a value attribute and handle them using an event handler.

import React from 'react';
function App() {
const [language, setLanguage] = useState("");
handleChange = (event) => {
 setlanguage(event.target.value)
}
  return (
    <form>
        <select value={language} onChange={handleChange}>
        <option value="html">HTML</option>
        <option value="css">CSS</option>
        <option value="javascript">JavaScript</option>
       <option value="reactjs">React Js</option>
        </select>
    </form>
  )
}
Export default App;

Multiple Input Fields

If you have to create a form with multiple input fields then you will have to declare a name attribute and value attribute as well within each input field and handle them with a single Event Handler

Example –

import React from 'react';
class App extends from React.Component {
state = {
  fullName:"",
  password:"",
  intro:""
}
let handleChange = (event) => {
  this.setState({[event.target.name]:event.target.value})
}
render(){
  return (
    <form onSubmit={handleSubmit}>
        <input name="fullName" type="text"  value={this.state.fullName} onChange={this.handleChange} />
        <input name="password" type="password"  value={this.state.password} onChange={this.handleChange} />
        <textarea name="intro" value={this.state.intro} onChange={this.handleChange} />
    </form>
  )
}
}
Export default App;

Uncontrolled Component

The value of a form input Field  is controlled by the DOM is called Uncontrolled Component

In case of Uncontrolled Component, You can use a ref  to access value of an form input from the DOM.

You need not use the Event Handler and value attribute if you implement an Uncontrolled Commponent in your form.

What is refs

Refs is a simple way to access react elements or DOM nodes as well.

Using refs, you can –

  • integrate, focus, text selection, media playback & animations
  • also integrate with third party DOM libraries

Create refs

You can create refs using React.createRef() and pass to React Elements using a ref attribute.

  • You  always have to create refs within the contruct method of a component
  • You can’t use a ref attribute within functional component because they don’t have instances
import React from "react";
class App extends React.Component {
  constructor(props) {
    super(props);
    this.refName = React.createRef();
  }
  render() {
    return <input ref={this.refName} />;
  }
}

Access refs

When a ref attribute pass to a react element, you can accces it’s reference node using current attribute

let node = this.refName.current;

Example –

In this example, we will apply foucus on the text input  using uncontrolled component.

import React from 'react';
class App extends from React.Component {
constructor(){
super(props);
this.textInput =React.createRef();
}
componentDidMount = () =>{
 this.textInput.current.focus();
}
render(){
  return (
    <form onSubmit={handleSubmit}>
        <input type="text" ref= {this.textInput} />
    </form>
  )
}
}
Export default App;

Also, You can access value of an input field after submiting the form

import React from 'react';
class App extends from React.Component {
constructor(){
super(props);
this.state ={
 inputData =""
}
this.textInput = React.createRef();
}
handleSubmit = (event) =>{
  event.preventDefault();
 this.setState({inputData: this.textInput.current.value()})
}
render(){
  return (
    <form onSubmit={handleSubmit}>
        <label>You Entered:{this.state.inputData}</label>
        <input type="text" ref= {this.textInput} />
        <input type="submit">
    </form>
  )
}
}
Export default App;