Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

error
react
reactjs

How to show an error message in React

Educative Answers Team

Displaying proper error messages is an essential aspect of error handling.

In this shot, we will go over a simple way to show error messages in React applications.

Simple, straightforward method

One way to display error messages is to have a state that stores them.

Let’s call this state errorMessage:

const [errorMessage, setErrorMessage] = useState('');

Now, whenever we encounter an error, we just update the errorMessage state:

setErrorMessage('Example error message!');

Then, display the error message using React conditional rendering. To keep things simple, we can just write an inline conditional statement:

{errorMessage && (
  <p className="error"> {errorMessage} </p>
)}

Now, let’s put it all together. Here we have a button that, once clicked, displays the error message:

import React from 'react';
import ReactDOM from 'react-dom';
require('./style.css');

function App() {
  const [errorMessage, setErrorMessage] = React.useState("");
  const handleClick = () => {
    setErrorMessage("Example error message!")
  }
  return (
    <div className="App">
      <button onClick={handleClick}>Show error message</button>
      {errorMessage && <div className="error"> {errorMessage} </div>}
    </div>
  );
}

ReactDOM.render(
  <App />, 
  document.getElementById('root')
);

RELATED TAGS

error
react
reactjs
Copyright ©2022 Educative, Inc. All rights reserved
RELATED COURSES

View all Courses

Keep Exploring