React
Styled-components props 전달
일단두잇
2023. 2. 18. 11:31
반응형
Styled-components를 사용하면 React에서 쉽게 css를 적용한 component를 생성할 수 있습니다.
CSS in JS : styled-components
https://styled-components.com/ 1. styled-components 사용하기전에 Template Literal에 대해 먼저 알아...
blog.naver.com
예를 들어 아래와 같이 Title이란 컴포넌트를 styled-components를 만들었다고 가정한다면,
아래와 같습니다.
import styled from 'styled-components';
export const Title = styled.div`
line-height: 48px;
color: #a2a2a2;
font-weight: 600;
font-size: 1.5rem;
`;
이떄, 해당 component의 color를 props로 전달하여 구현하고자 한다면,
props를 이용하여 구현할 수 있습니다. (es6 문법을 사용하면 props를 생략할 수 있습니다.)
${(props) => props.color
import styled from 'styled-components';
export const Title = styled.div<{ color?: string }>`
line-height: 48px;
color: ${(props) => props.color || '#a2a2a2'};
//color: ${({ color }) => color || '#a2a2a2'};
//color: #a2a2a2;
font-weight: 600;
font-size: 1.5rem;
`;
아래와 같이 사용할 수 있습니다.
<Title color="white">제목</Title>
반응형