[react]e.Stoppropagation

HOU·2024년 11월 20일
0

frontend

목록 보기
18/20
post-thumbnail

이벤트 버블링과 stopPropagation, preventDefault를 활용한 React 코드

리액트에서 이벤트 제어는 컴포넌트 구조에 따라 중요성이 더 커집니다. stopPropagationpreventDefault는 이벤트 처리와 상태 관리에서 강력한 도구가 됩니다. 아래는 이 두 가지를 활용한 React 코드와 함께 상황별 예제입니다.


1. 기본 이벤트 버블링 예제

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;

결과:

  1. 버튼을 클릭하면 콘솔 출력:
    Child Clicked!
    Parent Clicked!

2. 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;

결과:

  1. 버튼을 클릭하면 콘솔 출력:
    Child Clicked!
  2. 부모 요소의 클릭 이벤트는 실행되지 않습니다.

3. 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;

결과:

  1. 링크를 클릭하면 콘솔 출력:
    Link Clicked, but prevented default!
  2. https://example.com으로 이동하지 않습니다.

4. stopPropagationpreventDefault 함께 사용하기

모달 안의 버튼 클릭 이벤트에서 이벤트 전파와 기본 동작을 모두 막아야 할 때 유용합니다.

코드 예제:

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;

결과:

  1. 버튼을 클릭하면 콘솔 출력:
    Button Clicked, preventing both default and propagation!
  2. 모달 배경의 클릭 이벤트는 실행되지 않습니다.

5. 리액트에서 stopPropagationpreventDefault 사용 시 주의점

  1. 과도한 사용 지양:

    • stopPropagation은 부모와 자식 간의 이벤트 흐름을 막기 때문에, 의도적으로 사용하지 않으면 디버깅이 어려워질 수 있습니다.
  2. React의 SyntheticEvent:

    • React의 이벤트 시스템은 SyntheticEvent를 사용합니다. e.stopPropagation()e.preventDefault()는 이 SyntheticEvent에 적용되므로 DOM 이벤트와 약간의 차이가 있을 수 있습니다.
  3. 컴포넌트 구조 최적화:

    • 이벤트 처리기를 올바른 컴포넌트에 배치하면 stopPropagation의 필요성을 줄일 수 있습니다.

6. 요약

메서드기능주요 사용 사례
stopPropagation이벤트가 부모 요소로 전파되는 것을 막음자식 컴포넌트의 이벤트를 부모와 분리하고 싶을 때
preventDefault이벤트의 기본 동작(예: 링크 이동, 폼 제출 등)을 차단기본 동작을 방지하고 커스텀 로직을 실행하고 싶을 때
함께 사용이벤트 전파와 기본 동작 모두 막아야 할 때버튼 클릭 시 모달 내부에서만 동작하거나, 특정 입력 검증 시

React에서 이벤트 흐름을 제어하는 것은 종종 간단하지만 강력한 패턴입니다. 위의 예제를 통해 실제 프로젝트에 유용하게 활용해 보세요! 😊

profile
하루 한 걸음 성장하는 개발자

0개의 댓글

관련 채용 정보