Israel Martins
Israel Martins

Reputation: 318

How to get a React component in a function by onClick

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

Answers (4)

Harsh Makadia
Harsh Makadia

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

sultan
sultan

Reputation: 4739

Make code short and simple:

onClick = event => {
  console.log(event.target)
}
render() {
  return <button id="btn" onClick={this.onClick}></button>
}

Upvotes: 1

Tomasz Bubała
Tomasz Bubała

Reputation: 2153

You didn't pass the event to function call. Pass the event like this: onClick={(evt) => this.getcomponent(evt)}.

Upvotes: 1

DevK
DevK

Reputation: 9962

Add event as a parameter to the onClick:

render() {
    return (<button id="btn" onClick={(event) =>this.getcomponent(event)}></button>);
}

Upvotes: 1

Related Questions