I have created 2 components in a parent child relation. The first component is using refs and in componentDidMount I added a click event listener on the DOM node, in the child component also I added a onclick listener but this time using the props on the DOM element.
But now when I click the child component the event listener of the parent component is getting invoked, and if I add the onClick on parent component using the props instead of refs everything works fine.
So, can anybody tell me why this behaviour is shown when we add event listener using the refs.
class SecondDiv extends React.Component {
divClicked = (event) => {
event.stopPropagation();
console.log('Second Div clicked');
}
render() {
return <div className="Div2" onClick={this.divClicked} >
This is second div
</div>
}
}
class MovieItem extends React.Component {
constructor(props) {
super(props);
this.node = React.createRef();
}
componentDidMount() {
this.node.current.addEventListener('click', this.divClicked);
}
componentWillUnmount() {
this.node.current.removeEventListener('click', this.divClicked);
}
divClicked = (event) => {
event.stopPropagation();
console.log('First div clicked');
}
render() {
// 1st approach
return <div ref={this.node} className="Div1" >
<p>This is Div 1</p>
<SecondDiv />
</div>
// 2nd approach
// return <div ref={this.node} className="Div1" onClick={this.divClicked} >
// <p>This is Div 1</p>
// <SecondDiv />
// </div>
}
}
ReactDOM.render(<MovieItem />, document.getElementById("app"));
<div id="app"></div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>