Search

컴포넌트를 다양한 컨텍스트에서 사용하도록 모듈화

모듈화 고려하기

모듈화를 위해 보다 범용적으로 사용할 수 있는 버튼 컴포넌트의 이름을 고려할 때, 그 기능을 명확하게 하면서도 다양한 컨텍스트에서 사용할 수 있도록 해야 한다.

예를 들어

1.
PrimaryButton - 주요 작업을 위한 버튼으로 사용될 때
2.
ActionButton - 사용자의 행동을 유발하는 버튼으로 사용될 때
3.
NavigationButton - 페이지 내 또는 다른 페이지로의 네비게이션 목적으로 사용될 때
4.
InteractiveButton - 클릭 시 특정 인터랙션을 제공할 때

예시 코드

// Button.tsx import styled from '@emotion/styled'; import React from 'react'; import { Link } from 'react-router-dom'; import ButtonStyle from './Button.style'; import ButtonProps from './Button.type'; export const PrimaryButton: React.FC<ButtonProps> = ({ children, to, onClick }) => { return to ? ( <StyledLink to={to}> <ButtonStyle>{children}</ButtonStyle> </StyledLink> ) : ( <ButtonStyle onClick={onClick}>{children}</ButtonStyle> ); };
JavaScript
복사

변경 후 효과

렇게 변경함으로써, PrimaryButtonto prop을 받아 내부적으로 Link 컴포넌트로 동작하거나, onClick 이벤트 핸들러를 받아 일반적인 버튼으로 동작할 수 있다. 이는 코드의 재사용성을 높이고, 버튼의 사용 목적에 따라 유연하게 적용할 수 있게 해준다.

 랜덤 추첨기 전체 기록 보러 가기