React: React.cloneElement onClick does not work?

Created on 9 Feb 2016  路  6Comments  路  Source: facebook/react

Hi. Im trying to add an onClick handler to an already existing element.

Example:

render() {
    let element = <ImageCardView title="Test" subtitle="Subtitle" />;
    return React.cloneElement(element, { onClick: function() { console.log("TEST"); }});
}

// Result: Nothing happens when i click on the element

When setting it directly in the <ImageCardView /> it works.

Most helpful comment

Why is this closed?

All 6 comments

I found out that i cannot set a onClick handler directly to the component. Inside of the component i have to do something like:

// ImageCardView
render() {
  return <div onClick={this.props.onClick}>Test</div>
} 

Why is this closed?

Because its not a bug. You have to do for example:

class MyComponent extends React.Component {
  render() {
    return <button onClick={this.props.onClick}>Test</button>;
  }
}

class Wrapper extends React.Component {
  doSomething() {
    console.log("clicked :)");
  } 

  render() {
    return <MyComponent onClick={this.doSomething} />
  }
}

Why is it not a bug?
Your reply just requested a different solution. There wasn't any discussion over why the previous one was not working though. :)

Why is it not a bug?
Your reply just requested a different solution. There wasn't any discussion over why the previous one was not working though. :)

Looks like OP's original problem wasn't understood by himself 馃槤 The onClick handler lives on a child of ImageCardView rather than itself.

I found out that i cannot set a onClick handler directly to the component. Inside of the component i have to do something like:

// ImageCardView
render() {
  return <div onClick={this.props.onClick}>Test</div>
} 

I found out that i cannot set a onClick handler directly to the component. Inside of the component i have to do something like:

// ImageCardView
render() {
  return <div onClick={this.props.onClick}>Test</div>
} 

this resolve my problem

Was this page helpful?
0 / 5 - 0 ratings