React.cloneElement onClick does not work?
See original GitHub issueHi. 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.
Issue Analytics
- State:
- Created 8 years ago
- Reactions:4
- Comments:8
Top Results From Across the Web
reactjs - Add events to cloned component - Stack Overflow
How can I add a click event to this cloned component and call a function within its class when clicked? I have tried...
Read more >Using the React.cloneElement() function to clone elements
In this in-depth tutorial, learn how to clone and manipulate elements three different ways using the React.cloneElement function.
Read more >Override or set property to React element - DEV Community
This was usually a problem for me when building reusable components. ... The utility I am referring to is the cloneElement function exposed....
Read more >How to use the react.cloneElement function in react - Snyk
cloneElement function in react. To help you get started, we've selected a few react examples, based on popular ways it is used in...
Read more >cloneElement - React Docs
If you don't pass any ...children arguments, the original element.props.children will be preserved. Returns. cloneElement returns a React element object ...
Read more >
Top Related Medium Post
No results found
Top Related StackOverflow Question
No results found
Troubleshoot Live Code
Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free
Top Related Reddit Thread
No results found
Top Related Hackernoon Post
No results found
Top Related Tweet
No results found
Top Related Dev.to Post
No results found
Top Related Hashnode Post
No results found
Why is this closed?
Wow I’m so surprised this issue existed for so long without a clear explanation. Let me fill this gap for those who are going to search for it in the future. TLDR, it invokes props directly on your component, not the JSX you render
Let’s say we have a parent component:
And a child component:
And then we render it as following:
What’s happening with child component is that
React.cloneElement
only addsonClick
function to the list of props you are passing down to child prop. It does not invoke this prop in the JSX you declare. The solution here is as simple as it can be - just addonClick
handler to the component you render:It’s just the way our brain is messing with us and React have nothing to do with not handling clicks on your component 😃