Search code examples
javascriptreactjsreact-toastify

How to display toast using react-toastify inside class component when props check is true


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

Solution

  • 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