How to use react-toastify for notifications in React


In react, toastify is used to notify clients when they are clicking on a button to let them know that everything is OK or something went wrong
In this article we are going to explain how to use react toastify in react app
Install react-toastify
To install it use :
npm i react-toastify
yarn add react-toastify
Next, we need to import react-toastify CSS file and container in our js files so it can be used
The import look like this :
import { toast ,ToastContainer} from "react-toastify";
import 'react-toastify/dist/ReactToastify.css';
Test the configuration
Now to test the toasts, edit your app.js and use the following:
import { toast ,ToastContainer} from "react-toastify";
import 'react-toastify/dist/ReactToastify.css';
export default function App() {
const onClick = () => toast("Success notification", { type: "success" });
return (
<>
<button onClick={onClick}> Click Me</button>
<ToastContainer />
</>
);
}
Once done, save the file, run your server and goto localhost:3000 , and click on the button on the top left of the screen
The toast will look like this:
Customize react-toastify
Toast position
You can also custmoize the toast position, for example to show it on top left or down right
For example to set the toast on the bottom right, use the toast options like this:
toast('Toast is good', { hideProgressBar: true, autoClose: 2000, type: 'success' ,position:'bottom-right' })
Auto close
auto close specify in milliseconds how much time the toast will be visbile bofore auto closing
use it like this:
toast('Toast is good', { autoClose: 5000 })
This will close the toast after 5 seconds
Toast type
Use it with values like info, warning , error ...
toast('Toast is good', { type: 'error' })
This will display a toast with error
Conclusion
We have seen how to display toasts in react and how to customize the toast message, type and position