Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

onClick does not work for custom component

Tags:

reactjs

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?

like image 797
kojow7 Avatar asked Aug 17 '17 05:08

kojow7


People also ask

How do I beat onClick as a prop?

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.


2 Answers

@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>
)
like image 122
thinhvo0108 Avatar answered Sep 26 '22 05:09

thinhvo0108


You can provide onClick and other events only on DOM elements.

like image 41
Anurag Awasthi Avatar answered Sep 24 '22 05:09

Anurag Awasthi