Develop/React.js

[React][오류] 클릭 이벤트 전파 막기

dawonny 2023. 5. 17. 02:32
728x90
반응형

문제

 

채팅 리스트들을 보여주고, 채팅을 삭제할 수 있는 기능을 구현 중이었다.

채팅 리스트를 클릭하면 채팅을 확인하러 상세페이지로 이동하고,

삭제 버튼을 누르면 채팅 기록이 삭제가 되어야한다.

<div className="relative h-full overflow-y-scroll">
  {chats.map((chat) => (
    <div
      key={chat.chatId}
      onClick={() => handleChatItemClick(chat.chatId)}
      className="border-2 border-t-gray-300 p-5 flex justify-between text-sm"
    >
      {/* 채팅 생성 시간 */}
      <div>{formatDate(chat.created_date)}</div>
      <div className="">
        <button
          onClick={() => handleDeleteOneChat(chat.chatId)}
          className="px-4 py-2 overflow-hidden"
        >
          삭제
        </button>
      </div>
    </div>
  ))}
</div>

 

근데 삭제 버튼을 눌렀을 때 삭제가 되긴하지만 동시에 뒤에 div 리스트 요소도 눌려서 상세페이지로 이동까지 해버리는 것이었다.

 

해결

원인은 버튼을 클릭했을 때 이벤트가 상위 요소로 전파되었기 때문이다.

그래서 button 을 눌렀을 뿐인데 handleDeleteOneChat 과 handleChatItemClick 함수가 모두 실행된 것이었다.

 

이럴땐 event.stopPropagation() 을 추가하면 된다.

버튼을 클릭했을 때 버튼 이외의 부분에는 클릭 이벤트가 전달되지 않도록 할 수 있다.

수정된 코드는 다음과 같다.

            <div className="relative h-full overflow-y-scroll">
                {chats.map((chat) => (
                    <div
                        key={chat.chatId}
                        onClick={() => handleChatItemClick(chat.chatId)}
                        className="border-2 border-t-gray-300 p-3 flex justify-between text-sm"
                    >
                        {/* 채팅 생성 시간 */}

                        <div className="flex items-center">
                            {formatDate(chat.created_date)}
                        </div>
                        {/* 채팅 삭제 버튼 */}

                        <button
                            className="px-4 py-2 overflow-hidden"
                            onClick={(event) => {
                                event.stopPropagation(); // 이벤트 전파 중지
                                handleDeleteOneChat(chat.chatId);
                            }}
                        >
                            삭제
                        </button>
                    </div>
                ))}
            </div>

이러면 버튼 부분에서는 버튼 이벤트만 일어나도록 할 수 있다.

728x90
반응형