Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Passing current element to onClick function - React Jsx

I have a div, i want to pass this div to onlick function and change it's class (or add class).

<div className="history-node" onClick={() => this.handleHistoryClick(this)}>
     <span className="history-title">Uploaded</span>
     <span className="history-date">October 9, 2017</span>
</div>

Function is:

handleHistoryClick(el){
      console.log("History Clicked");
      console.log(el);
}

But this is printing current React Component Class which is Paymentdetail.

What i want is:

handleHistoryClick(el){
     $(el).addClass('active');
}

EDIT: I have multiple history-node elements. So adding state to change class won't work for multiple elements.

How do i achieve this?

like image 776
Noman Ali Avatar asked Oct 18 '17 13:10

Noman Ali


People also ask

Which value should you pass to event listener props like onClick?

Pass a Button's Value as a Parameter Through the onClick Event Handler. You might want to pass in the value or name of the button or input element through the event handler.

How do you pass an event argument in react?

Passing the event object of react as the second argument. If you want to pass a parameter to the click event handler you need to make use of the arrow function or bind the function. If you pass the argument directly the onClick function would be called automatically even before pressing the button.


2 Answers

this in your code refer to the component and not the element:

<div className="history-node" onClick={() => this.handleHistoryClick}>
     <span className="history-title">Uploaded</span>
     <span className="history-date">October 9, 2017</span>
</div>

component :

handleHistoryClick(event){
      let el = event.target;
      el.classList.add('active');
      // $(el).addClass('active'); I'm not familiar with jquery but try it
}

edit : As @sag1v said : it is better to bind the handler in the constructor (or use arrow function) instead of creating a new function instance on each render. just like this :

constructor(){
   this.handleHistoryClick= this.handleHistoryClick.bind(this);
}
like image 102
El houcine bougarfaoui Avatar answered Nov 15 '22 08:11

El houcine bougarfaoui


Instead of using this.handleHistoryClick(this)}>

use this...

this.handleHistoryClick.bind(this)}>

like image 42
SVD Avatar answered Nov 15 '22 08:11

SVD