프론트엔드 앱/React-native

React Native에서 styled-components로 기존 컴포넌트 스타일링하기

세리둥절 2021. 12. 7. 20:47
반응형

✔️ 필요성

React Native에서 컴포넌트를 이미 만들어둔 다음에, 사용할 때 margin이나 padding만 조금 더 추가해서 쓰고 싶은 적 없으신가요?!! 맨처음부터 확정된 margin을 줘버리면 나중에 위치 레이아웃할 때 싹 다 꼬인다구요!

 

그러면서도 CSS와 JS를 깔끔하게 분리해서 코드 짜고싶은 마음 저만 있는거 아니죠...? styled-components를 활용하면 가능합니다.

 

 

✔️ 참고

styled-components 공식 문서를 보면 나와있긴 합니다만

 

styled-components: Basics

Get Started with styled-components basics.

styled-components.com

 

 

✔️ 활용 예제

SectionTitle이라고 메뉴의 타이틀을 나타내는 글자 컴포넌트를 만들었습니다. 나중에 마진을 추가로 줄 때는 Text 태그가 아니라 Text를 감싸고 있는 View 태그를 꾸밀 것이기 때문에 View 태그에 style이라는 props를 추가합니다.

 

React에서는 className이라는 props를 사용했는데 React Native에서는 style이라는 이름을 사용해야 합니다 (공식문서 참조)

import React from 'react';
import styled from 'styled-components/native';

const Title = styled.Text`
  font-weight: bold;
  font-size: 18px;
`;

// 기본 마진을 얹어줌
const TitleContainer = styled.View<{style: React.ReactNode}>`
  margin-vertical: 10px; 
`;

interface Props {
  text: string;
  style?: React.ReactNode;
}

const SectionTitle = ({text, style}: Props) => {
  return (
    <TitleContainer style={style}> // View태그에 style props 추가
      <Title>{text}</Title>
    </TitleContainer>
  );
};

export default SectionTitle;

 

만들어둔 SectionTitle에다가 가로 마진을 추가해서 사용하고 싶을 때는 아래처럼 styled-component로 기존 컴포넌트를 감싸서 사용하면 됩니다. 이 때 추가로 지정하는 CSS는 아까 style props를 지정한 View 태그에 추가됩니다!

import React from 'react';
import styled from 'styled-components/native';
import SectionTitle from '~/components/SectionTitle';

// 추가로 가로 margin을 얹어줍니다
const StyledTitle = styled(SectionTitle)`
  margin-horizontal: 10px; 
`;
반응형