How to display success, error message in ReactJS

Showing an error or success message is too common in all kinds of applications. Sometimes we have to display a validation error message like “Not a correct email or password” and sometimes we have to display a success message like “User registration is Successful”, “Password matched”

So, In this article, we will learn how to show an error or a success message to the user in reactJS.

To display the messages, let’s create a simple rectJS application that contains a simple password and confirm password input field to show the user the success message or an error based on the input values that the user has written in both of the input fields.

Steps:

  • Create a react project.
  • Create a form with input fields.
  • Implement error-handling functionality.

Create a React project

  • Open the command prompt and write the below commands to create and run a react project
    npx create-react-app my-app
    cd my-app
    npm start
    
  • Go inside the project folder and open app.js file which is in the src folder of the project folder.

import React, { useState, useEffect } from "react";
const App = () => {
  
  return (
    <div className="w-2/3 mx-auto">
      

    </div>
  );
}

export default App

Note: Whatever we write inside the div will be visible in the browser. To know more about creating a project in Reactjs, please read this article.

Create a form with input fields

  • Create a form that will contain two input fields for password and confirming that password and a button.
<div className="form-control items-center lg:items-start">
  <input  required type="password" placeholder="password" className="input input-bordered w-full max-w-md " />
</div>

<div className="form-control items-center lg:items-start">
  <input required type="password" placeholder="confirm password" className="input input-bordered w-full max-w-md " />
</div>
import React, { useState, useEffect } from "react";
const App = () => {
 
  return (
    <div className="w-2/3 mx-auto">
      <form  className="card-body  my-20 p-0">
        
        <div className="form-control items-center lg:items-start">
          <input required type="password" placeholder="password" className="input input-bordered w-full max-w-md " />
        </div>

        <div className="form-control items-center lg:items-start">
          <input  required type="password" placeholder="confirm password" className="input input-bordered w-full max-w-md " />
        </div>

        <div className="form-control items-center lg:items-start mt-6">
          <button type="submit" className="btn btn-sm w-full max-w-md">Check Password</button>
        </div>
      </form>

    </div>
  );
}

export default App

Note: we are using Tailwind CSS to make the form look better. Read this article to more about it.

Display success, error message in ReactJS

So, finally, we have all the resources ready, Now we need to implement the last step “Implement error-handling” to display the error or success message.

Implement error-handling functionality
  • Declare three states with useState() a hook to handle the input values and the error/success message.
// state for get the password
  const [password, setPassword] = useState('');
  // state for getting confirm password
  const [confirmPassword, setConfirmPassword] = useState('');

  // error/success
  const [errorOrSuccess, setErrorOrSuccess] = useState({
    error: true,
    success: false
  });
  • Declare onChange() event handler to both of the input fields and set the password state according to the changed value.
<div className="form-control items-center lg:items-start">
          <input onChange={e => setPassword(e.target.value)} required type="password" placeholder="password" className="input input-bordered w-full max-w-md " />
        </div>

        <div className="form-control items-center lg:items-start">
          <input onChange={e => setConfirmPassword(e.target.value)} required type="password" placeholder="confirm password" className="input input-bordered w-full max-w-md " />
        </div>
  • Create onSubmit() handler in the form and declare a function to handle the submission of the form.
<form onSubmit={handleSubmit} className="card-body  my-20 p-0">
 // handle form submission
  const handleSubmit = e => {

  };
  • Declare a condition to compare both the input field values whether they are the same or not.
// handle form submission
 const handleSubmit = e => {
   e.preventDefault();
   if (!password.length || !confirmPassword.length) {
     setErrorOrSuccess({ error: true, success: false })
   }
   if (password !== confirmPassword) {
     setErrorOrSuccess({ error: true, success: false })
   } else {
     setErrorOrSuccess({ error: false, success: true })
   }
 };

Here, first condition is if one of the two input fields is empty, we will show an error. And second condition is if the value of those fields are not the same, we’ll show an error as well. And lastly, if both of them are the same, we will show a success message.

  • Declare <p> tag with conditional error or success message in it. Based on the error or successtion, the <p> tag will show the user a success or an error message.
<p className="text-error">{errorOrSuccess.error && "Password doesn't match or the field is empty"}</p>
<p className="text-success">{errorOrSuccess.success && "Password matched"}</p>
import React, { useState, useEffect } from "react";
const App = () => {
  // state for get the password
  const [password, setPassword] = useState('');
  // state for getting confirm password
  const [confirmPassword, setConfirmPassword] = useState('');

  // error/success
  const [errorOrSuccess, setErrorOrSuccess] = useState({
    error: true,
    success: false
  });


  // handle form submission
  const handleSubmit = e => {
    e.preventDefault();
    if (!password.length || !confirmPassword.length) {
      setErrorOrSuccess({ error: true, success: false })
    }
    if (password !== confirmPassword) {
      setErrorOrSuccess({ error: true, success: false })
    } else {
      setErrorOrSuccess({ error: false, success: true })
    }
  };
  return (
    <div className="w-2/3 mx-auto">
      <form onSubmit={handleSubmit} className="card-body  my-20 p-0">
        <p className="text-error">{errorOrSuccess.error && "Password doesn't match or the field is empty"}</p>
        <p className="text-success">{errorOrSuccess.success && "Password matched"}</p>
        <div className="form-control items-center lg:items-start">
          <input onChange={e => setPassword(e.target.value)} required type="password" placeholder="password" className="input input-bordered w-full max-w-md " />
        </div>

        <div className="form-control items-center lg:items-start">
          <input onChange={e => setConfirmPassword(e.target.value)} required type="password" placeholder="confirm password" className="input input-bordered w-full max-w-md " />
        </div>

        <div className="form-control items-center lg:items-start mt-6">
          <button type="submit" className="btn btn-sm w-full max-w-md">Check Password</button>
        </div>
      </form>

    </div>
  );
}

export default App

With emty values,

With mismatched values,

With matched values,

This is how we can handle an error or a succession message in ReactJS.