1

I am working on react project where i am trying to display toast using react-toastify , inside a div section when props ( isNotificationOpen ) is true. I tried an example something like bellow but i dont want the toast be triggered when button press occurs , i want the the tost to be triggered when isNotificationOpen props is set to true , how can i achieve this?

const notify = () => toast("Wow so easy !");

render() {
    return (
      <div className="d-flex" style={{ margin: "25px" }}>
        <div className="mr-auto p-2">
          {this.props.isNotificationOpen ? (
            <div>
              <div>
                <button onClick={notify}>Notify !</button>
                <ToastContainer />
                </div>
              //Show toast here...
              </div>
          ) : (
            <p />
          )} ```
Divakar R
  • 773
  • 1
  • 8
  • 36

1 Answers1

2

Use a component lifecycle function to respond to the isNotificationOpen prop changing to trigger a notfication.

Class-based component example

notify = () => toast('Wow so easy!');

componentDidMount() {
  const { isNotificationOpen } = this.props;
  isNotificationOpen && this.notify();
}

componentDidUpdate(prevProps) {
  const { isNotificationOpen } = this.props;
  
  if (prevProps.isNotificationOpen !== isNotificationOpen) {
    isNotificationOpen && this.notify();
  }
}

Functional component example

useEffect(() => {
  props.isNotificationOpen && toast('Wow so easy!');
}, [props.isNotificationOpen]);

Edit how-to-display-toast-using-react-toastify-inside-class-component-when-props-chec

Drew Reese
  • 165,259
  • 14
  • 153
  • 181
  • Thansks for the answer I am using components class, and i did just add this code in inside my render() and later i added a function on top , it worked :) ```
    {this.notify()} < ToastContainer />
    ```
    – Divakar R Oct 21 '20 at 10:00
  • You where spot on my next issue and exactly correct , that warning really turned out to be an issue to me now as i am setting the prop value to go false based on (setTimeout) seconds my toast was getting displayed multiple times , i am currently working around ```componentDidMount ``` and ```componendDidUpdate```, fix this , Thank you – Divakar R Oct 21 '20 at 15:56