1

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
                    }));
                  }}
                }

2 Answers2

2

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)}}
johnborges
  • 2,422
  • 20
  • 33
James Delaney
  • 1,765
  • 1
  • 17
  • 36
0

what you want is

onClick={this.props.location==='/favorites' ? null : 
   () => {
      this.props.updateFavsState(this.props.character);
      this.setState(prevState => ({
          loved: !prevState.loved
      }));
}}       
Tiago Coelho
  • 5,023
  • 10
  • 17