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.
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') );
Free Resources