One tip and how to solve your problem (In two ways)
Tip: Not usually the best idea to mix React
with jQuery
. React came in as a major paradigm shift in how we interact with the DOM
. Try to read a little bit more about React, how it works, why is it so different from simply adding/removing elements in the DOM
with jQ.
Some references to help you with that:
How to go from jQuery to React.js?
Thinking in React for jQuery Programmers
Now, back to your question
You should use currentTarget
.
As the .history-title
and .history-date
elements are wrapped within .history-node
, any click on them will trigger it's parent's event, since .history-node
body is .history-title
+ .history-date
. That's the correct behavior. When you trigger an event in JS, the event
object receives two parameters: target
, which is the event triggering the event and currentTarget
, the element that is actually listening for the event.
Now for the code:
with JQ
Component:
<div className="history-node-container" key={index}>
<div className="history-node" onClick={handleHistoryClick}>
<span className="history-title">{heading.action}</span>
<span className="history-date">{moment(heading.added_at).format("MMMM Do, YYYY")}</span>
</div>
</div>
Click:
handleHistoryClick(event){
$('.history-node').removeClass('active')
event.currentTarget.classList.add('active')
}
The React way (Pure React, no modules)
Component:
class HistoryNode extends Component {
constructor(props) {
super(props)
this.state = { isActive: false }
this.handleClick = this.handleClick.bind(this)
}
handleClick(e) {
let state = this.state
this.setState({isActive: !state.isActive})
}
render() {
return(
<div className="history-node-container">
<div className={`history-node ${this.state.isActive ? 'active' : ''}`} onClick={handleHistoryClick}>
<span className="history-title">{heading.action}</span>
<span className="history-date">
{moment(heading.added_at).format("MMMM Do, YYYY")}</span>
</div>
</div>
)
}
}
Notice how you don't need to manipulate the DOM
at any moment at the React solution. You just attach your event to that particular component, define how it's state change should reflect on the UI and let React do the rest.
Hope it helps ;)
Reference for target
vs currentTarget