Why does onClick not work directly on my custom element as shown here? The function chosenResource does not get invoked.
return (
<div>
{
resources.map(resource => {
return (
<SelectListItem key={resource.id} onClick={this.chosenResource.bind(this)} resource={resource} />
)
})
}
</div>
)
However, if I encapsulate my custom element in a div element and have the onClick on the div element then it works.
return (
<div>
{
resources.map(resource => {
return (
<div key={resource.id} onClick={this.chosenResource.bind(this)}>
<SelectListItem resource={resource} />
</div>
)
})
}
</div>
)
What is wrong with the first approach?
When you add an onClick prop to the LinkButton component, it is just a property of an object. By calling props. onClick from inside of that component you are just calling a function that is stored inside of a property, similar to this: let props = { onClick: function () { alert("Executed!"); } }; props.
@nrgwsth is correct, if you still want to stick with your first approach, you may use:
return (
<div>
{
resources.map(resource => {
return (
<SelectListItem key={resource.id} customClickEvent={this.chosenResource.bind(this)} resource={resource} />
)
})
}
</div>
)
Then, in your SelectListItem's render()
function, use like this:
return (
<div onClick={this.props.customClickEvent}>
...
</div>
)
You can provide onClick
and other events only on DOM elements.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With