How to handle two functions onClick

Tags: ,



In my Class component App.jsx I have the following function:

import { Position } from "./Position";
...

getPositionData = val => {
    const { players } = this.props;       
    var res = players.filter(o=>Object.values(o).includes(val))        
    return res
  };

Which is being handled at render() when I click on a subcomponent inside a <div>, like so:

<div className="field-row"> 
   {this.getPlayersByPosition(players, 4).map((player,i) => (
      <Position key={i} handleClick={this.getPositionData}>{player.name}</Position>
    ))} 
</div>

On its turn, Position.jsx handles onClick():

export const Position = props => (
  <div
    className={`position-wrapper ${
      isManager(props.children) ? null : "field"
    }`}
    onClick={() => props.handleClick(props.children)}
  >
    {props.children}
  </div>
);

But now I’d like to handle a second function when <div> is clicked, say:

 toggleFullScreen() {
    this.setState({ fullScreen: !this.state.fullScreen });
  }

which I would pass, on its own, like so:

onClick={this.toggleFullScreen.bind(this)}

How do I handle BOTH functions onClick() at once in

<div className="field-row"> 
...
</div>

?

Answer

Just like you can invoke multiple functions at once in a JS listener with

element.addEventListener('click', () => {
  fn1();
  fn2();
});

You can do the same thing in React by defining the onClick to be a function which invokes both:

<Position
  key={i}
  getPositionData={this.getPositionData}
  toggleFullScreen={toggleFullScreen}
>{player.name}</Position>
export const Position = props => (
  <div
    className={`position-wrapper ${
      isManager(props.children) ? null : "field"
    }`}
    onClick={() => {
      props.getPositionData(props.children);
      props.toggleFullScreen();
    }}
  >
    {props.children}
  </div>
);


Source: stackoverflow