Can we pass multiple event handlers as props and choose a specific one to attach to a child component?


#1

Question

In the context of this exercise, can we pass multiple event handlers as props and choose a specific one to attach to a child component?

Answer

Yes! You can pass in multiple event handlers as props to the child component, then to choose a specific one to attach to it you can utilize something like a ternary statement.

For example, say that you have a component whose button should run different code based on its state. We can pass the functions to the child component, then from the child component, use a ternary statement that will attach one of the two functions based on its state.

The parent component might look like the following, which passes two event handlers to its child component.

class Parent extends React.Component {
  handleClickOne() {
    // Code
  }
  
  handleClickTwo() {
    // Code
  }
  
  render() {
    return <Child onClickOne={this.handleClickOne} 
                  onClickTwo={this.handleClickTwo} />;
  }
}

Then, the child component will receive both event handlers, and attach one of them to itself, based on its state.

class Child extends React.Component {
  render() {
    return (
      <button onClick={this.state.value == someValue ? 
                       this.props.onClickOne : this.props.onClickTwo}>
        Click me!
      </button>
    );
  }
}

FAQ: this.props - Receive an Event Handler as a prop