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.