stopPropagation
, preventDefault
를 활용한 React 코드리액트에서 이벤트 제어는 컴포넌트 구조에 따라 중요성이 더 커집니다. stopPropagation
과 preventDefault
는 이벤트 처리와 상태 관리에서 강력한 도구가 됩니다. 아래는 이 두 가지를 활용한 React 코드와 함께 상황별 예제입니다.
React에서 이벤트는 기본적으로 버블링됩니다. 자식 컴포넌트에서 이벤트가 발생하면 부모 컴포넌트까지 전달됩니다.
import React from "react";
const Parent = () => {
const handleParentClick = () => {
console.log("Parent Clicked!");
};
return (
<div onClick={handleParentClick} style={{ padding: "20px", backgroundColor: "lightgray" }}>
<Child />
</div>
);
};
const Child = () => {
const handleChildClick = () => {
console.log("Child Clicked!");
};
return (
<button onClick={handleChildClick}>Click Me</button>
);
};
export default Parent;
Child Clicked!
Parent Clicked!
stopPropagation
으로 이벤트 버블링 중단stopPropagation
을 사용하여 이벤트가 부모 요소로 전파되지 않도록 합니다.
import React from "react";
const Parent = () => {
const handleParentClick = () => {
console.log("Parent Clicked!");
};
return (
<div onClick={handleParentClick} style={{ padding: "20px", backgroundColor: "lightgray" }}>
<Child />
</div>
);
};
const Child = () => {
const handleChildClick = (e) => {
e.stopPropagation(); // 이벤트 버블링 중단
console.log("Child Clicked!");
};
return (
<button onClick={handleChildClick}>Click Me</button>
);
};
export default Parent;
Child Clicked!
preventDefault
로 기본 동작 차단링크를 클릭했을 때 페이지 이동을 막고, 클릭 이벤트를 커스터마이징합니다.
import React from "react";
const PreventDefaultExample = () => {
const handleLinkClick = (e) => {
e.preventDefault(); // 기본 동작(페이지 이동) 차단
console.log("Link Clicked, but prevented default!");
};
return (
<a href="https://example.com" onClick={handleLinkClick}>
Prevent Default Link
</a>
);
};
export default PreventDefaultExample;
Link Clicked, but prevented default!
https://example.com
으로 이동하지 않습니다.stopPropagation
과 preventDefault
함께 사용하기모달 안의 버튼 클릭 이벤트에서 이벤트 전파와 기본 동작을 모두 막아야 할 때 유용합니다.
import React from "react";
const ModalExample = () => {
const handleModalClick = () => {
console.log("Modal Background Clicked!");
};
const handleButtonClick = (e) => {
e.stopPropagation(); // 이벤트 버블링 중단
e.preventDefault(); // 기본 동작 차단
console.log("Button Clicked, preventing both default and propagation!");
};
return (
<div
onClick={handleModalClick}
style={{
display: "flex",
justifyContent: "center",
alignItems: "center",
height: "100vh",
backgroundColor: "rgba(0,0,0,0.5)",
}}
>
<div style={{ backgroundColor: "white", padding: "20px", borderRadius: "5px" }}>
<button onClick={handleButtonClick}>Click Me</button>
</div>
</div>
);
};
export default ModalExample;
Button Clicked, preventing both default and propagation!
stopPropagation
과 preventDefault
사용 시 주의점과도한 사용 지양:
stopPropagation
은 부모와 자식 간의 이벤트 흐름을 막기 때문에, 의도적으로 사용하지 않으면 디버깅이 어려워질 수 있습니다.React의 SyntheticEvent:
SyntheticEvent
를 사용합니다. e.stopPropagation()
과 e.preventDefault()
는 이 SyntheticEvent에 적용되므로 DOM 이벤트와 약간의 차이가 있을 수 있습니다.컴포넌트 구조 최적화:
stopPropagation
의 필요성을 줄일 수 있습니다.메서드 | 기능 | 주요 사용 사례 |
---|---|---|
stopPropagation | 이벤트가 부모 요소로 전파되는 것을 막음 | 자식 컴포넌트의 이벤트를 부모와 분리하고 싶을 때 |
preventDefault | 이벤트의 기본 동작(예: 링크 이동, 폼 제출 등)을 차단 | 기본 동작을 방지하고 커스텀 로직을 실행하고 싶을 때 |
함께 사용 | 이벤트 전파와 기본 동작 모두 막아야 할 때 | 버튼 클릭 시 모달 내부에서만 동작하거나, 특정 입력 검증 시 |
React에서 이벤트 흐름을 제어하는 것은 종종 간단하지만 강력한 패턴입니다. 위의 예제를 통해 실제 프로젝트에 유용하게 활용해 보세요! 😊