[Next.js, TypeScript] 커스텀컴포넌트 만들기

Yeong·2024년 12월 31일
post-thumbnail

프로젝트 초기 구조를 설계하면서 버튼 공통컴포넌트를 생성하는데 한 컴포넌트만 대표적으로 정리해보면좋을 것 같아 남겨보는 기록!

1. 공통컴포넌트.tsx 생성

src> components> CutomButtom 폴더 내에 CutomButtom.tsx와 CutomButtom.scss 생성

//CutomButtom.tsx

"use client"

import {PropsCustomButton} from "../../../next-env";
import Image from "next/image";

const CustomButton = ({ title, handleClick, btnType = "button", textStyles, rightIcon, isDisabled = false, className = ""}: PropsCustomButton) => {
    return (
        <button
            className={`custom-btn ${className}`} // className은 추가될 수 있도록 설정
            type={btnType}
            disabled={isDisabled}
            onClick={handleClick}
        >
            <span className={`flex-1 ${textStyles}`}>{title}</span>

            {rightIcon && (
                <div>
                    <Image src={rightIcon} alt="icon" fill className='object-contain' />
                </div>
            )}
        </button>
    );
}

export default CustomButton
  • next.js는 서버사이드 렌더링이 기본이기 때문에 브라우저의 상황에 따라 움직이는 button은 client side 렌더링이다. (onClick요소)
    그렇기에 상단에 use client 를 선언해주어야한다.
  • 먼저 뼈대 구조를 잡아준 뒤에, 커스텀을 위한 버튼의 props를 지정한다.(버튼의 이름, 클릭시 작동하는 함수, 버튼의 타입, 그리고 각각의 style등등...)
  • :PropsCusomButton은 내가 next-env.d.ts 파일 내 선언한 타입명이다.

2. next-env.d.ts 내 타입 선언 (버튼의 props type 정해주기)

type PropsCustomButton = {
    title:string;
    handleClick?: MouseEventHandler<HTMLButtonElement>;
    btnType?: "button" | "submit";
    textStyles?: string;
    rightIcon?: string;
    isDisabled?: boolean;
    className?: string;
}

types 폴더를 만들어 커스텀 버튼의 type을 지정해주기도하는데, 나는 next-env.d.ts 내에서 한번에 관리했다.

3. CustomButton.tsx에서 type넣어주기

1번 내 코드를 참고하면된다.(type을 넣어주면됨)
그리고 import {PropsCustomButton} from "../../../next-env"; 를 import해주어야한다.

4. 해당 컴포넌트 사용하기

"use client";

import CustomButton from "@/components/CustomButton/CustomButton";

export default function List() {
    function handleClick() {
        console.log('스크롤이 동작합니다.');
    }
    return (
        <div>
            <h2>Products</h2>
            <div className="food">
                <h4>상품명 $40</h4>
            </div>
            <div className="food">
                <h4>상품명 $40</h4>
            </div>
            <CustomButton title="GoodBye2024" handleClick={handleClick}  isDisabled={false} />
        </div>
    )
}

위와 같이 담아서 적용하면 끝!

5. scss 적용

@use "@/styles/index" as s;

.listBtn {
  background-color: blue;
  color: white;
  padding: 10px 20px;
  border-radius: 5px;
  border: none;
  cursor: pointer;
}

@mixin ButtonCommon {
  text-align: center;
  padding-top: 12px;
  width: 120px;
  height: 52px;
  color: pink;
}


.buttonCommon {
  @include ButtonCommon;

  span {
    background-color: #ffffff;
  }
}

css적용 시에 여러 클래스를 사용할 수 있다.

<CustomButton type="button" title="안녕" className="buttonCommon" />
또는
<CustomButton title="GoodBye2024" handleClick={handleClick}  isDisabled={false} className="listBtn" />

위와 같은 식으로 공통 버튼 컴포넌트여도 다양한 클래스를 지정할 수 있다.

0개의 댓글