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?
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?
Share Improve this question edited Oct 18, 2017 at 14:03 Noman Ali asked Oct 18, 2017 at 13:55 Noman AliNoman Ali 3,34013 gold badges47 silver badges79 bronze badges 3- Possible duplicate of react change class name on state change – azium Commented Oct 18, 2017 at 13:59
-
No it's not. Because i have multiple
history-node
elements. How to determine states for all of them? only one can haveactive
state. – Noman Ali Commented Oct 18, 2017 at 14:01 - store an array of states then, not just one – azium Commented Oct 18, 2017 at 14:20
2 Answers
Reset to default 9this
in your code refer to the ponent 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>
ponent :
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)}>