React

[React] - styled-components로 html태그 동적생성하기

위르겐 2023. 6. 14. 01:24

styled-components로 같은 스타일을 입히지만

각기 다른 html태그를 사용해야 될 때가 있다.

 

예를 들어

p태그, h1태그, span태그 등은

모두 문자를 표현하는 마크업 언어지만

성질이 다르다.

 

이 때 다른 성질을 유지하면서도

스타일을 같게 유지하려면 

styled-component에서

as prop을 사용하면 된다.

 

 ( 타입스크립트입니다. )

const Typography = ({ as = "p", color, children, ...props }: Props) => { 
return ( 
    <DynamicTypography as={as} color={color}>
    {children}
    </DynamicTypography>
    )
}

 

위와 같은 Typography라는 컴포넌트를 만들어서

DynamicTypography 를 리턴해주자

 

여기서 DynamicTypography는

Styled-component이다.

 

분명

DynamicTypography에 

as라는 props를 넘겨주고 있지만

해당 스타일드 컴포넌트에서 as를 props로 선언해주지 않아도

타입에러가 나지 않는다.

 

export const DynamicTypography = styled.p<{
  color: string;
}>`
  color: ${({ color }) => color}
`;

 

여기서 만약 color라는 props를 지정해주지 않는다면 

문제가 되겠지만

as는 styled-components자체에서 제공해주는

props기능이기 때문에

p태그가 기본으로 먹혀있는 이 컴포넌트에

as가 자동으로 덮어진다.

그러므로

span이든 h1태그든 button태그든 입힐 수 있게 되는 것이다.

 

 <Typography as="span" color="#ffffff">hi~!</Typography>

사용하려는 곳에선 

as="span"처럼

원하는 태그를 props문자열로 넘겨주기만하면 된다.

 

 

 

 

https://styled-components.com/docs/api#as-polymorphic-prop

 

styled-components: API Reference

API Reference of styled-components

styled-components.com

 

진리는 공식문서에....

 

 

반응형