[Meet Errors] React + TypeScript + Emotion 환경에서 props에 기초한 스타일링 변화 감지를 못하는 에러 해결 방법

kyle kwon·2022년 11월 23일
0

MeetError

목록 보기
4/4
post-thumbnail

Error


// App.tsx

import styled from '@emotion/styled'
import Button from './components/commons/Button'

export interface ButtonProps {
  backgroundColor: string
  fontColor: string
  fontSize: string
}

function App() {
  const issueBtn: ButtonProps = {
    backgroundColor: 'green',
    fontColor: 'white',
    fontSize: '14px',
  }

  return (
    <>
      <Nav>
        <h1>hello</h1>
      </Nav>
      <Header>header</Header>
      <ListContainer>listcontainer</ListContainer>
      <Footer>footer</Footer>
      <Button issueBtn={issueBtn} />
    </>
  )
}

// Button.tsx

import styled from '@emotion/styled'
import { ButtonProps } from '../../App'

const Button = ({ issueBtn }: { issueBtn: ButtonProps }) => {
  const { backgroundColor, fontColor, fontSize } = issueBtn
  return (
    <C.Button background={backgroundColor} color={fontColor} fontSize={fontSize}>
      New Issue
    </C.Button>
  )
}

export default Button

const C: any = {}

C.Button = styled.button`
  padding: 5px 1rem;
  border-radius: 6px;
  border: 1px solid rgba(27, 331, 0.1);
  ${({ color }) => color && `color: ${color}`};
  ${({ background }) => background && `background-color: ${background}`};
  ${({ fontSize }) => fontSize && `font-size: ${fontSize}`}
`

공통으로 사용될 버튼 컴포넌트를 만드는 과정에서 다음과 같은 에러를 마주하게 되었습니다. button DOM 요소에 background를 props로 넘겨, Emotion을 활용한 props 기반 스타일링을 하는 과정에서 위와 같은 에러를 마주하였습니다.

background에 대한 Type 지정이 명시되어 있지 않아 그렇습니다.


Solution

C.Button = styled.button<{ color: string; background: string; fontSize: string }>`
  padding: 5px 1rem;
  border-radius: 6px;
  border: 1px solid rgba(27, 331, 0.1);
  ${({ color }) => color && `color: ${color}`};
  ${({ background }) => background && `background-color: ${background}`};
  ${({ fontSize }) => fontSize && `font-size: ${fontSize}`}
`

props로 받아온 issueBtn을 destructuring 한 후에, 해당되는 값 3개를 다시 props로 넘긴 상황에서, props에 기초한 변화 스타일링을 주기 위해, 마치 제네릭의 형태로 해당 props마다 type을 명시해 주어야 합니다.

추가적으로 유의할 점

위의 App 컴포넌트에서 issueBtn을 props로 넘기고, Button 컴포넌트에서 props로 받는 상황에서, 해당 props를 destructuring한 값인 issueBtn을 받는 것이기 때문에, {issueBtn} : {issueBtn : ButtonProps}로 타입을 명시해줘야 합니다.

profile
FrontEnd Developer - 현재 블로그를 kyledot.netlify.app으로 이전하였습니다.

0개의 댓글