Search code examples
reactjsternary

Conditional onClick from ternary


I'm trying to have an onClick event fire depending on the location of the user. if the location is '/favorites' i want to return null i've tried using a ternary operator to achieve this, and cannot find my mistake. heres what i've tried:

             {this.props.location==='/favorites' ? null : 
                onClick={() => {
                    this.props.updateFavsState(this.props.character);
                    this.setState(prevState => ({
                      loved: !prevState.loved
                    }));
                  }}
                }

Solution

  • Put logic in the function and call function onClick event, location pass to the function as argument.

    Solution:

    handleClick = (location) => {
      if (location === '/favorites') {
        return null;
     }
      this.props.updateFavsState(this.props.character);
      this.setState(prevState => ({
        loved: !prevState.loved
      });
    }
    
    // somewhere in your render component
    onClick={() => { handleClick(this.props.location)}}