이벤트 버블링???

자식에서 이벤트가 발생했을때, 이것이 부모요소들의 이벤트까지 트리거 시키는 현상을 말한다. 그러므로, parent > child1 > child2가 있고 각각 콜백함수 p, c1, c2가 있다고 할때, c2 → c1 → p순서로 차례대로 실행되게 될 것이다.

이러한 전파를 막고 싶을 때가 있다.

Untitled

예를 들어, 위의 전체 카드를 클릭했을때, 상세 페이지가 보여지게 하고 싶고, 하트를 눌렀을때 좋아요 기능을 하게 하고 싶다고 가정하자. 이러한 이벤트 버블링 때문에, 우리가 좋아요(최하위컴포넌트)를 눌렀을때, 자동적으로 상세페이지도 커져버리게 된다.

도대체 어떻게 이런 이벤트 버블링을 막을 수 있는지 정리해 보자.

이벤트 버블링 방지 방법

event.stopPropagation(); 여기서, Propagation은 번식이라는 뜻이며, 즉 부모로 부터 생산되어진 이벤트를 막는다는 것을 의미한다. (상세페이지로 가지게 되는 부모의 이벤트를 막는 다는 뜻이다!) 부모의 이벤트를 자식입장에서 막는 것이므로, 반드시 자식 컴포넌트에서 해당 코드를 작성하자!

최상단의 자식 컴포넌트의 이벤트에 아래와 같이 작성해 준다. 
const clickHandler = event => {
		event.stopPropagation();
		//sth that you want, in this clickHandler
}

React-Router의 클릭 방지 방법

위의 방식으로 하면, 일반적인 이벤트는 막아지나, <Link to='/'>와 같은 부모를 가진 자식 컴포넌트에서는 방지가 되지 않는다. 이럴때는 아래와 같이 e.preventDefault()를 사용하자

최상단의 자식 컴포넌트의 이벤트에 아래와 같이 작성해 준다. 
const clickHandler = event => {
		event.preventDefault();
		//sth that you want, in this clickHandler
}

The stopPropagation() method prevents propagation of the same event from being called. Propagation means bubbling up to parent elements or capturing down to child elements. Whereas The preventDefault() method cancels the event if it is cancelable, meaning that the default action that belongs to the event will not occur. In this case, we have a 'native' html event (or at least its emulation in JS), therefore we want to cancle the default action. Sources: w3schools.com/jsref/event_stoppropagation.asp w3schools.com/jsref/event_preventdefault.asp)

출처: https://github.com/remix-run/react-router/issues/6010