Search code examples
reactjstoastreact-toastify

React-toastify notification won't return in conditional


The notification works quite easily with a button. However, I'm trying to have it activate when a props passes through (true/false).

Basically, the user clicks on this tab, if they're not signed in, it'll pop up with the notification telling them to sign in.

However, I cannot make it work without being a button. The props passess through just fine, and I can console.log it. And the conditional returns... something, but it's like an odd bunch of letters, and each refresh it changes. And does not pop up like a notification. It's just obscure letters in the middle of the screen (because of {notify} placed above the form).

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

    class Alerts extends Component {
      constructor(props){
        super(props)
        this.state = { 
          alertLogin: ''
        }
      }

      render() {

        const notify = () => toast("Please login before adding a recipe!");

        // tried to make a conditional to check if prop alertLogin is true or false
        // then calls notify function if false 
        if (!this.props.alertLogin) {
          console.log('alert props received', this.props.alertLogin)
          return notify()
        }

        return ( 
        <div>
          {/* <button onClick={notify}>Notify !</button> */}
          {notify}
          <ToastContainer />
        </div>
        );
      }
    }
    
    export default Alerts;

Solution

  • import React, { Component } from "react";
    import "./styles.css";
    import { ToastContainer, toast } from "react-toastify";
    import "react-toastify/dist/ReactToastify.css";
    class Alerts extends Component {
      constructor(props){
        super(props)
        this.state = { 
          alertLogin: ''
        }
      }
      componentDidMount() {
        // tried to make a conditional to check if prop alertLogin is true or false
        // then calls notify function if false
        if (!this.props.alertLogin) {
          console.log("alert props received", this.props.alertLogin);
          this.notify();
        }
      }
      notify = () => toast("Please login before adding a recipe!");
      render() {
        return (
          <div>
            <button onClick={(e) => this.notify()}>Notify !</button>
            <ToastContainer />
          </div>
        );
      }
    }
    export default Alerts;
    

    Codepen for the solution

    First you take the if statement with the function and put it in componentDidMount cause i'm guessing is stopping the rendered elements themselves from rendering second make the toast function accessible by component did mount and the button by declaring it before the render function hope i was clear enough