본문 바로가기
Develop/Web

React 취소 버튼 컴포넌트 만들기

by 라이프레이서 2021. 4. 24.
반응형

React는 반복 사용되는 컴포넌트를 만들어두고 어느 곳에서든 재사용 할 수 있다는 장점을 갖고 있습니다.

이번 포스팅에서는 프로젝트를 만들며 빈번하게 사용되는 취소 버튼을 컴포넌트로 만들고 이용하는 방법에 대해 적어보겠습니다.

 

1. CancelButton.jsx 만들기

import React from "react";
import { css } from "@emotion/css";

export default function CancelButton({cancelAction}) {
  return (
    <div>
      <button
        className={css`
          border: 1px solid #bdbdbd;
          box-sizing: border-box;
          border-radius: 12px;
          font-style: normal;
          font-weight: normal;
          font-size: 24px;
          line-height: 28px;
          color: #bdbdbd;
          padding: 12px 42px;
          :hover{
            background: #bdbdbd;
            color: #ffffff;
          }
        `}
        onClick={cancelAction}
      >
        취소
      </button>
    </div>
  );
}

취소 버튼을 컴포넌트로 따로 제작해둡니다.

index.jsx를 만들어 해당 컴포넌트를 빼주는 것도 잊지 마세요!

components의 index.jsx

2. 취소 버튼에 동작 넣기

취소 버튼의 행동에는 여러가지가 있을 수 있습니다.

 

모달 창의 취소 버튼이라면, 해당 모달 창을 사라지게 하는 경우, 뒤로가기와 같은 기능을 하는 경우 등이 있겠죠.

 

이번 포스팅에서는 뒤로가기 버튼과 동일한 기능을 하도록 작업했습니다.

위의 history의 정의는 다음과 같습니다.

import { useHistory } from "react-router-dom";

// react-router-dom의 useHistory()
const history = useHistory();

완성

 

반응형