Masoud92m
Masoud92m

Reputation: 622

How to handler onClick on child component in parent component

my App component like as below:

class App extends Component {
  clickHandler = () => {
    console.log('click');
  }
  render() {
    return (
      <div className="App">
        <div onClick={this.clickHandler}>Test1</div>
        <Person onClick={this.clickHandler}>Test2</Person>
      </div>

    );
  }
}

And this is my Person component:

class Person extends Component {
    render() {
        return (
            <div>{this.props.children}</div>
        )
    }
}

When i click on Test1 onClick works and show click on console, but when i click on Test2 onClick doesn't work. how to i handler onClick in parent component? i don't want pass onClick to child component.

Upvotes: 5

Views: 26348

Answers (4)

AbhaY
AbhaY

Reputation: 126

class Person extends Component {
    render() {
        return (
            <div onClick={propes.onClick}>{props.children}</div>
        )
    }
}

Upvotes: 0

Dan
Dan

Reputation: 10538

You need to pass onClick to the <div> in Person.

onClick is not a special prop that works everywhere in React - The only intrinsic props are key and children. Everything else needs to be wired up manually.

The reason your code doesn't work is because you're passing onClick to Person, but to the Person component, onClick is just another prop. It does nothing on it's own until you pass it to a component that understands what it means to handle a click event (which all of the built-in components in React do).

Upvotes: 1

onejeet
onejeet

Reputation: 1191

Here is the complete solution... Checkout: https://codesandbox.io/s/vjp200rj3

Modified render function in App.

render() {
    return (
      <div className="App">
        <div onClick={this.clickHandler}>Test1</div>
        <Person clickHandler={this.clickHandler}>Test2</Person>
      </div>
    );
  }

Modified render function in Person:

  render() {
    return <div onClick={this.props.clickHandler}>{this.props.children}</div>;
  }

Upvotes: 1

Yossi
Yossi

Reputation: 6027

This should work. Why don't you want to write it this way? You ARE passing it as a prop...

<div onClick={props.onClick}>Test</div>

Upvotes: 5

Related Questions