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 />
          )} ```

1 Answer 1

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

Sign up to request clarification or add additional context in comments.

2 Comments

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 :) <div>{this.notify()} < ToastContainer /> </div>
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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.