DEV Community

Cover image for Simple alert notification for your react app
Ali Zulfaqar
Ali Zulfaqar

Posted on

Simple alert notification for your react app

react-toastify

react-toastify is a npm package to replace your default alert notification on the browser.

Installation

Use the node package manager (npm) to install react-toastify.

react-toastify

npm install --save react-toastify
Enter fullscreen mode Exit fullscreen mode

Usage with class component

 import React from 'react';
 import { ToastContainer, toast } from 'react-toastify';
 import 'react-toastify/dist/ReactToastify.css';

class App extends React.Component {

onClick = () => {
  toast.info("Info")
  toast.success("Success");
  toast.warning("Warning");
  toast.error("Error");
  toast.default("Default");
  toast.dark("Dark");
}
render() {
  return (
   <>
    <div>
    <button onClick={this.onClick}>Notify!</button>
    <ToastContainer />
    </div>
   </>
)}
}
Enter fullscreen mode Exit fullscreen mode

Usage with functional component

  import React from 'react';

  import { ToastContainer, toast } from 'react-toastify';
  import 'react-toastify/dist/ReactToastify.css';

  function App(){
    const notify = () => {
      toast.info("Info")
      toast.success("Success");
      toast.warning("Warning");
      toast.error("Error");
      toast.default("Default");
      toast.dark("Dark");
    }

    return (
      <div>
        <button onClick={notify}>Notify!</button>
        <ToastContainer />
      </div>
    );
  }
Enter fullscreen mode Exit fullscreen mode

By default, ToastContainer have the attributes as below

<ToastContainer
  position="top-right"
  autoClose={5000}
  hideProgressBar={false}
  newestOnTop={false}
  closeOnClick
  rtl={false}
  pauseOnFocusLoss
  draggable
  pauseOnHover
/>
{/* Same as */}
<ToastContainer />
Enter fullscreen mode Exit fullscreen mode

Conclusion

With a few steps to install the package and usage with code, you now have a colourful alert to use to make it more attractive for user, thank you for your time.

Discussion (1)

Collapse
ibrahimfikry profile image
Ibrahim Fikry Abd Nasir

Nice