Form Handling in ReactJS


In this article, we are going to see how to handle the forms properly in a React application.

Handling Forms is one of the most crucial parts needed while building a real-world React application. It is all about taking the inputs from the user, validating it and displaying if there are errors in the data submitted by the user.

Example

In this example, we will build an Information Page that takes the information from the user, validates it and displays the result accordingly.

Here, we have App.js as the parent component of the Details.js component.

Details.js

import React, { useState } from 'react';

const Details = () => {
   const [name, setName] = useState('');
   const [number, setNumber] = useState(null);
   const [mssg, setMssg] = useState(null);

   const submit = (e) => {
      e.preventDefault();
      if (!Number(number)) {
         setMssg('Phone Number should be of number type only');
      } else {
         setMssg('Form Submitted!');
      }
   };
   return (
      <form onSubmit={submit}>
      <input
      placeholder="Name"
      value={name}
      onChange={(e) => setName(e.target.value)}
      />

      <input
      placeholder="Phone Number"
      value={number}
         onChange={(e) => setNumber(e.target.value)}
      />
      <button>Submit</button>
      {mssg}
      </form>
   );
};
export default Details;

App.js

import React from 'react';
import Details from './Details';

const App = () => {
   return (
      <div>
      <h1>Information Page:</h1>
      <Details />
      </div>
   );
};
export default App;

In the above example, we are taking the inputs from the user and storing it in the state of the application. If the phone number entered by the user is not of number type, then the error message will be displayed.

Output

This will produce the following result.

Updated on: 18-Mar-2021

414 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements