kojow7
kojow7

Reputation: 11384

onClick does not work for custom component

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?

Upvotes: 26

Views: 30269

Answers (3)

StateLess
StateLess

Reputation: 5402

In react, we have components(ex. SelectListItem) and elements(ex.div). Elements are the basic building blocks for the component.

Elements are transpiled into plain javascript objects which represent DOM elements where we can bind the dom events like onCLick, onHover etc.

However Component returns the instance that contains a bunch of elements but does not correspond to the DOM element.

SO if you want to bind DOM event we should do it on the react elements, not in components.

In the above code, onClick event is passed down as props to the component which can be seen by logging the props of the compoenet.

Upvotes: 14

thinhvo0108
thinhvo0108

Reputation: 2232

@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>
)

Upvotes: 27

Anurag Awasthi
Anurag Awasthi

Reputation: 6223

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

Upvotes: 23

Related Questions