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?
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.
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.
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);
}
Instead of using this.handleHistoryClick(this)}>
use this...
this.handleHistoryClick.bind(this)}>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With