user10210735
user10210735

Reputation: 127

How to use 2 different values of 'THIS' in React

So I have this function inside a Component:

clickedResultHandler = (embedLink) => {
    this.setState({embedSrcLink: embedLink});
}

this function is called inside a descendant like this:

<div onClick={() => props.clickedResult(embedSrcLink)} className="result">

What I want to do is: when I click on this div (with className='result') I want do something with that div. meaning I need to access this keyword where this=the div that was clicked. But inside the function definition, I also need to access this where this=the Component itself where the function is defined so that I may set the state.

I've looked around and still haven't found a solution.

Thanks

Upvotes: 2

Views: 34

Answers (2)

Andrei Todorut
Andrei Todorut

Reputation: 4526

You have to pass the Event parameter to the clickedResultHandler method.

clickedResultHandler = (embedLink) => (e) {
    // e.currentTarget is your div
    this.setState({embedSrcLink: embedLink});
}

Upvotes: 2

McRist
McRist

Reputation: 1748

You will get event.target like this:

<div onClick={(event) => props.clickedResult(event, embedSrcLink)} className="result">

clickedResultHandler = (event, embedLink) => {
    console.log(event.target);
    this.setState({embedSrcLink: embedLink});
}

The target event property returns the element that triggered the event.

You can also use event.currentTarget which always refers to the element whose event listener triggered the event.

Upvotes: 4

Related Questions