I have many buttons each with their one onClick function. Does onClick take care of handling the eventListener and parcelling out the event to the correct function automatically, or do I need to test that the event is for my function?
What if I also have added eventListeners for the click event? In those event listeners I check that the event target is for the correct function. But will React also pass a click to the onClick() functions too ? How does React differentiate between onClick() handlers and addEventListener("click") handlers ?
For example, in my class component I have:
export class MyPage extends React.Component {
constructor(props) {
super(props);
...
}
componentDidMount() {
this.attachEventHandlers();
...
}
attachEventHandlers() {
window.addEventListener("click",this.ontoggleExpandUpper.bind(this));
window.addEventListener("click",this.ontoggleExpandLower.bind(this));
...
}
ontoggleExpandUpper(){
if (!(event.target.classList.contains('uexp'))) return;
...
}
ontoggleExpandLower(){
if (!(event.target.classList.contains('lexp'))) return;
...
}
toggleSidebar() {
this.setStateOnMount((state) => ({
...state, sidebarOpen: !state.sidebarOpen
}));
}
render() {
//first a couple with onClick()
<button className="open-sidebar btn btn-dark btn-lg shadow" onClick {() => this.toggleSidebar()}>
<i className="open-sidebar"></i>
</button>
<button className="toggle-sidebar-closed btn btn-dark" onClick={() => this.toggleSidebar()}>
<i className="fi flaticon-cancel"></i>
</button>
//next a couple with addEventListener()
<button id="uexp" className="uexp">
<i id="iuexp" className="uexp"></i>
</button>
<button id="lexp" className="lexp">
<i id="ilexp" className="lexp"></i>
</button>
}
}
In your example, you're adding an event listener to a window object, which means it'll be triggered for every click, no matter which DOM element you click. Typically, you want to add the listener only to an element you're actually interested about, e.g. document.querySelector('.uexp').addEventListener('click', event => this.onToggleExpandUpper(event)). This way, you don't have to check if event target is correct, because onToggleExpandUpper() will be called only when you click the correct element.
React will take care of registering event listeners for you. When you set onClick it will automatically get added to a correct element. You should prefer onClick attribute over manually adding event listeners, because it's more declarative.