How to show an error message in React

Key takeaways:

  • React's useState Hook is used to store error messages dynamically, allowing you to update and manage error states efficiently.

  • Errors can be updated in response to user actions, such as form submissions or API responses, by setting the error message state with a relevant message.

  • Error messages are displayed conditionally using inline conditional rendering ({errorMessage && ...}), ensuring the UI remains uncluttered and only shows messages when necessary.

  • Error messages should be cleared when issues are resolved, such as after successful form submissions, by resetting the state to an empty string.

Displaying proper error messages is an essential aspect of error handling in React applications. It helps users understand what went wrong and how to proceed. In this Answer, we’ll explore a straightforward method to show error messages in React using React state and conditional rendering.

Why handle errors properly?

Error handling ensures that your application provides a user-friendly experience even when things go wrong. By displaying clear, user-friendly error messages in React, you can guide users to fix mistakes, like missing form fields or invalid data, and prevent frustration.

Using state to store error messages

In React, one way to display error messages is to have a state that stores them. We can create a state variable called errorMessage that will hold any error messages that need to be displayed.

const [errorMessage, setErrorMessage] = useState('');
  • errorMessage: This state holds the current error message.
  • setErrorMessage: This function updates the errorMessage state.

Updating the error message

Whenever an error occurs in the application, you can update the errorMessage state with the relevant message:

setErrorMessage('Example error message!');

This could be triggered by events like form submissions, API responses, or user interactions (e.g., clicking a button).

Displaying error messages conditionally

Using React’s conditional rendering, you can display the error message only when it exists. This keeps your UI clean and only shows the message when there’s actually an error:

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

This inline conditional checks if errorMessage is not empty, and if true, it renders the error message inside a <p> element with the error class for styling.

Coding example

Now, let’s put it all together. Here, we have an input field and a button. When the button is clicked, the application:

  • Either displays the square root of the entered number if positive.
  • Or shows an error message if the entered number is negative.
import React from 'react';
import ReactDOM from 'react-dom';
import './style.css'; // Import your styles

function App() {
  const [inputValue, setInputValue] = React.useState(""); // Track user input
  const [result, setResult] = React.useState(""); // Store the result
  const [errorMessage, setErrorMessage] = React.useState(""); // Store error message

  const handleInputChange = (event) => {
    setInputValue(event.target.value);
    setErrorMessage(""); // Clear error when user starts typing
    setResult(""); // Clear result on new input
  };

  const handleCalculate = () => {
    const number = parseFloat(inputValue); // Parse the input

    // Check for errors
    if (isNaN(number)) {
      setErrorMessage("Please enter a valid number.");
      return;
    }
    if (number < 0) {
      setErrorMessage("Square root of a negative number is undefined.");
      return;
    }

    // Calculate square root
    setResult(`The square root of ${number} is ${Math.sqrt(number).toFixed(2)}.`);
  };

  return (
    <div className="App">
      <h1>Square Root Calculator</h1>
      <input
        type="text"
        value={inputValue}
        onChange={handleInputChange}
        placeholder="Enter a number"
      />
      <button onClick={handleCalculate}>Calculate Square Root</button>
      {errorMessage && <div className="error">{errorMessage}</div>}
      {result && <div className="result">{result}</div>}
    </div>
  );
}

ReactDOM.render(
  <App />,
  document.getElementById('root')
);
Displaying an error message on button click

Code explanation

In the above index.js file:

  • Lines 1–3: We import React and ReactDOM to create and render the component. Import the CSS file for styling.

  • Line 5: We define the App component using a function.

  • Lines 6–8: We define three state variables using useState:

    • inputValue to track the user’s input.

    • result to store the calculated square root or an empty string when cleared.

    • errorMessage to hold the error message to be displayed.

  • Lines 10–14: We implement the handleInputChange() function. Inside this function, we update the inputValue state as the user types and clear any previous error or result to provide immediate feedback for new input.

  • Lines 16–31: We define the handleCalculate() function. Inside this function, we convert the inputValue to a numeric value. We validate the input and display an error message if the input is not a number or is negative. Lastly, we calculate the square root for valid input and update the result state.

  • Lines 33–46: We render the component UI.

    • Line 34: We use a <div> with the class App to wrap the content for styling.

    • Line 35: We add a heading to label the application as a square root calculator.

    • Lines 36–41: We add an <input> field to accept user input bound to inputValue and attach the handleInputChange() function to update the state dynamically.

    • Line 42: We add a button labeled “Calculate Square Root” to trigger the handleCalculate() function.

    • Line 44: We conditionally render the error message using {errorMessage && ...}. The message is wrapped in a <div> with the error class for styling.

    • Line 45: We conditionally render the result using {result && ...}. The message is wrapped in a <div> with the result class for styling.

When to clear error messages

In a real-world application, you may want to clear the error message after a successful action or when the user corrects their input. You can do this by setting setErrorMessage('') when the error is resolved.

Knowledge test

Let’s attempt a short quiz to assess your understanding.

1

What is the purpose of using the useState Hook in a React component for error handling?

A)

To directly manipulate the DOM elements

B)

To store and update the state of error messages dynamically

C)

To define CSS styles for components

D)

To fetch data from an API asynchronously

Question 1 of 20 attempted

Conclusion

This method of handling error messages is simple yet effective for many scenarios. By using state and conditional rendering, you can ensure that your React applications provide users with clear and helpful feedback, improving the overall user experience. Implementing error message display techniques not only enhances usability but also aligns with React application best practices.

If you want to explore more about React, check out our blog, The best React developer roadmap for 2024, for in-depth insights into the latest React tools and best practices.

Frequently asked questions

Haven’t found what you were looking for? Contact Us


How to get error code in React

To get error codes in React, you can use error boundaries, which are React components that catch JavaScript errors in their child component tree during rendering, life cycle methods, and in constructors of the whole tree below them. You can implement an error boundary by defining a class component that includes the componentDidCatch life cycle method, which provides the error and error info. This method allows you to capture the error code and display a fallback UI or log the error for further analysis.


How to handle error in React?

Error handling in React can be accomplished by using try-catch blocks in asynchronous functions or by implementing error boundaries for class components. For instance, when fetching data or performing other operations that may fail, wrapping the code in a try-catch block allows you to catch any exceptions and set an error state accordingly. Additionally, for user input validation, you can check for errors before submitting the form and display appropriate error messages based on the validation results, ensuring a smoother user experience.


How to fix React errors?

Fixing React errors typically involves debugging the code and identifying the root cause of the issue. Common steps include reviewing the error messages in the console, which often provide helpful information about what went wrong and where it occurred. You can also leverage tools like React Developer Tools to inspect components and their states. Once you identify the issue, it may require adjusting your component logic, fixing state management, ensuring proper prop types, or handling asynchronous data correctly. Using thorough testing and console logging can further aid in resolving these errors effectively.


Free Resources

Copyright ©2025 Educative, Inc. All rights reserved