Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

REACT-Toastify - Duplicates toasts

I just added React-Toastify to my REACT app. I have the below code in my Apps.js

import { ToastContainer, Slide } from "react-toastify";
import "react-toastify/dist/ReactToastify.css";

function App() {
  return (
    <>
      <Router basename={process.env.PUBLIC_URL}>
        <div className="container-fluid">
          <NavHeader />
          <hr />
          <Switch>
            <Route exact path="/" component={HomePage} />
            <Route path="/about" component={AboutPage} />
            <Route path="/contact" component={ContactPage} />
          </Switch>
        </div>
      </Router>
      <div>
        <ToastContainer transition={Slide} />
      </div>
    </>
  );
}

export default App;

Then in my other pages, I display the Toast using the code below.

  showToastMessage(messageText, messageType = "I") {
    toast.dismiss();
    toast.configure({
      position: toast.POSITION.BOTTOM_RIGHT,
      toastId: 1
    });
    if (messageType === "S") {
      toast.success(messageText);
    }
    if (messageType === "I") {
      toast.info(messageText);
    }
    if (messageType === "E") {
      toast.error(messageText);
    }
  }

When I run the app, the toast is displayed in the bottom right and top right corner of my page.

I have done a lot of searches and did come across this thread and applied the changes suggested, but I am still getting duplicates!

like image 496
tcDev Avatar asked Dec 04 '19 18:12

tcDev


2 Answers

Add your <ToastContainer/> to App.tsx or whatever you named your default root App.js file. After that, DO NOT add <ToastContainer/> to elsewhere.

      <ToastContainer 
            position='top-right' 
            autoClose={5000}
            hideProgressBar={false}
            newestOnTop={false}
            closeOnClick
            rtl={false}
            pauseOnFocusLoss
            draggable
            pauseOnHover
        />  
like image 130
AlkanV Avatar answered Oct 19 '22 00:10

AlkanV


if you use ToastContainer and toast function each together, you will see two toastify. You should use only one.


Your code design some complex. Let me show how to use basic toastify you will understand it.

Firstyle import package. (Step 1)

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

Now, you can call toast. (Step 2)

 toast.configure();

 toast.success("Success Notification !", {
    position: toast.POSITION.TOP_CENTER
  });

  toast.error("Error Notification !", {
    position: toast.POSITION.TOP_LEFT
  });

  toast.warn("Warning Notification !", {
    position: toast.POSITION.BOTTOM_LEFT
  });

  toast.info("Info Notification !", {
    position: toast.POSITION.BOTTOM_CENTER
  });

that's it.

like image 26
Ali Yaman Avatar answered Oct 19 '22 00:10

Ali Yaman