1

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>);
  }

4 Answers 4

2

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;

Sign up to request clarification or add additional context in comments.

Comments

1

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

Comments

1

Add event as a parameter to the onClick:

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

Comments

1

Make code short and simple:

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.