Reputation: 318
I need to get a component that I cliked and see its target property. I try to get it but the evt param is undefined
getcomponent(evt){
console.log(evt.target)
//...
}
//...
render() {
return (<button id="btn" onClick={() =>this.getcomponent()}></button>);
}
Upvotes: 1
Views: 74
Reputation: 3443
You need to pass event in order to get it back. Here is the code.
class TestJS extends React.Component {
constructor(props) {
super(props);
this.getcomponent = this.getcomponent.bind(this);
}
getcomponent(event){
console.log(event.target);
}
render() {
return(
<div id="root">
<button id="btn" onClick={(event) =>this.getcomponent(event)}></button>;
</div>
)};
}
export default TestJS;
Upvotes: 2
Reputation: 4739
Make code short and simple:
onClick = event => {
console.log(event.target)
}
render() {
return <button id="btn" onClick={this.onClick}></button>
}
Upvotes: 1
Reputation: 2153
You didn't pass the event to function call. Pass the event like this:
onClick={(evt) => this.getcomponent(evt)}
.
Upvotes: 1
Reputation: 9962
Add event
as a parameter to the onClick
:
render() {
return (<button id="btn" onClick={(event) =>this.getcomponent(event)}></button>);
}
Upvotes: 1