I'm creating a React component (parent) that receives a link, button, or other React component (child) as a property, and I want to attach an additional click handler to the passed-in component. This child component usually already has a click handler defined, so I can't just add onClick
to it using React.cloneElement. Also, sometimes the child component's click handler prevents event propagation to the parent component, so I can't just attach the click listener to the parent and allow the event to bubble up.
Edit: The parent/child relationship and how/where the extra event listener should be attached makes this question slightly different from other questions I've seen, where the answer is to pass a callback (or array of callbacks) into the child component. I do not have access to alter the child component's API.
Here's some sample code:
export default class ParentComponent extends React.Component {
constructor(props) {
super();
this.handleClick = this.handleClick.bind(this);
}
handleClick(event) {
// do something (this is not working)
}
render() {
let { childComponent } = this.props;
return (
<div>
{React.cloneElement(childComponent, {
onClick: this.handleClick
})}
</div>
)
}
}
ParentComponent.PropTypes = {
childComponent: PropTypes.element
};