[emotion] props 전달 방법과 type 에러 해결방법

JunSeok·2022년 9월 28일
0

지식 기록

목록 보기
2/6
post-thumbnail

next.js로 프로젝트 작업을 하면서 스타일 작업은 emotion을 사용했다.

조건 반응형으로 스타일에 변화를 주기 위해서 emotion에 props를 전달해주기로 하였다.

// Theme.tsx
import { ThemeLikeBtn } from './Theme.style'

const Theme = () => {
	const [like, setLike] = useState(false);
  
  	const clickLikeBtn = () => {
    	try {
        	setLike(true)
        } catch(e) {
         	console.log(e.response) 
        }
    }
    
    return (
    	<ThemeLikeBtn like={like} onClick={clickLikeBtn}>
    )
}
// Theme.style.tsx

import styled from '@emotion/styled'

export const ThemeLikeBtn = styled.button`
	color: ${(props) => (props.like ? 'red' : 'white')}	
`

기본적으로는 위와 같이 사용한다.
하지만 저렇게만 했을 때는 typescript의 경우 다음과 같은 에러가 생길 수 있다.

'{ children: Element; like: boolean; onClick: () => Promise; }' 형식은 'IntrinsicAttributes & { theme?: Theme; as?: ElementType; } & ClassAttributes & HTMLAttributes<...>' 형식에 할당할 수 없습니다.
'IntrinsicAttributes & { theme?: Theme; as?: ElementType; } & ClassAttributes & HTMLAttributes<...>' 형식에 'like' 속성이 없습니다.ts(2322)

위와 같은 에러를 해결해주기 위해 import 해주는 emotion style에 type 설정을 해주면 된다!

// Theme.style.tsx
import styled from '@emotion/styled'

type ThemeLikeBtnProps = {
  like: boolean
}

export const ThemeLikeBtn = styled.button<ThemeLikeBtnProps>`
	color: ${(props) => (props.like ? 'red' : 'white')}	
`

위와 같이 type을 작성해주면 정상적으로 잘 동작한다!

참고자료

스택오버플로우

profile
최선을 다한다는 것은 할 수 있는 한 가장 핵심을 향한다는 것

0개의 댓글