React/링크게더 (리액트 프로젝트)

[React] - emotionJS + Typescript + props넘기기

위르겐 2023. 4. 8. 13:50

그동안 정신이 없어서

꽤 오랜만에 글을 남겨본다...ㅎㅎ

 

링크게더

사이드프로젝트를 진행하면서

단순히 굴러가게 만드는 게 아니라 

코드 컨벤션과 개발 문화를 정립하며

어떻게하면 반복을 줄이고 재사용할 수 있을 지를

많이 생각할 수 있게 됐다.

 

 

emotionJS로

styled component를 생성하여 재사용하고

props에 따라 조건적으로 다른 스타일을

보여주는 방법을 공유하고자 한다.

 

사실 styled component랑

크게 다를건 없지만

https://next--emotion.netlify.app/docs/typescript

 

Emotion - TypeScript

Emotion includes TypeScript definitions for @emotion/react and @emotion/styled. These definitions also infer types for css properties with the object syntax, HTML/SVG tag names, and prop types. @emotion/react TypeScript checks css properties with the objec

next--emotion.netlify.app

공식문서를 참고하여 좀 더 가독성 괜찮은 방법을 알게됐다.

 

const RequestButton = styled('button')<{ value: string }>(
  {
    width: '94px',
    height: '50px',
    fontSize: '14px',
    textAlign: 'center',
    fontWeight: '600',
    borderRadius: '8px',
    marginLeft: '10px',
  },
  (props) => ({
    border: props.value ? `2px solid ${palette.secondary.n300}` : `2px solid ${palette.secondary.n60}`,
    color: props.value ? palette.secondary.n300 : palette.secondary.n60,
    backgroundColor: palette.contrastText,
    cursor: props.value ? 'pointer' : 'null',
  })
);

 

고정적으로 사용하는 width 나 height같은 값은 별도로 두고

props에 따라 변하는 스타일 속성들을 객체로 따로 관리하여 

가독성이 좋은 방법이다.

 

가독성이나 코드스타일은

주관적이라고 볼 수 있지만

나의 경우엔 앞으로 이렇게 관리할 예정이다.

 

반응형