LeBlaireau
LeBlaireau

Reputation: 17467

Reactjs - passing a click event up to parent

On my child event I have

<div className="box" onClick={this.clickBox}></div>

On my parent I have the method

clickBox() {
  alert('hello');
}
and have bound it with

this.clickBox = this.clickBox.bind(this);

This does not work but if I put the method in the child it triggers.

How do I pass the event up to the parent?

Upvotes: 0

Views: 2168

Answers (1)

Hemerson Carlin
Hemerson Carlin

Reputation: 7424

You can send onClick as a prop to Child

const Child = ({ onClick }) => <div className="box" onClick={onClick}></div>

and then in the parent:

class Parent extends React.Component {
  constructor() {
    super()

    this.clickBox = this.clickBox.bind(this)
  }

  clickBox() {
    ...
  }

  render() {
    return (
      <div>
        <Child onClick={this.clickBox}
      </div>
    )
  }
}

Upvotes: 2

Related Questions