Reusable toast message component in React.js
Toast messages are a common way to display notifications or alerts to users in web applications. In React.js, we can create a reusable toast message component that can be easily integrated into any part of our app.
Creating the Toast component
First, we need to create a new component called Toast that will handle the rendering of our toast messages. This component will accept props such as message, type (success, error, warning), and onClose function.
const Toast = ({ message, type, onClose }) => (
<div className={`toast ${type}`} onClick={onClose}>
<p>{message}</p>
</div>
);
Styling the Toast component
We can add some CSS to style our toast messages. Here’s an example of how we can style the toast message for a success type:
.toast {
position: fixed;
top: 20px;
right: 20px;
background-color: #28a745;
color: white;
padding: 10px;
border-radius: 4px;
cursor: pointer;
}
Using the Toast component
Now that we have our Toast component created and styled, we can use it in our app whenever we want to display a toast message. Here’s an example of how we can use the Toast component in a React.js app:
function App() {
const [toast, setToast] = React.useState(null);
const showToast = (message, type) => {
setToast({ message, type });
setTimeout(() => {
setToast(null);
}, 3000);
};
return (
<div>
{toast && <Toast message={toast.message} type={toast.type} onClose={() => setToast(null)} />}
<button onClick={() => showToast('Success message', 'success')}>Show Success Toast</button>
</div>
);
}
With this setup, we can easily display toast messages in our React.js app whenever necessary. By creating a reusable Toast component, we can keep our code clean and maintainable.
Conclusion
Creating a reusable toast message component in React.js is a great way to easily display notifications or alerts to users in our web applications. By following the steps outlined in this article, you can quickly implement toast messages in your React.js app and make your user experience more interactive and engaging.