[React] styled-components 적용하기
by 배부른코딩로그💡 styled-components를 적용하는 김에 정리도 한 방에 해보자.
목표
- styled-components가 무엇인지 설명할 수 있다.
- styled-components를 적용해보고 간단한 예제를 작성할 수 있다.
- styled-components를 적용할 때, 쉽게 따라할 수 있는 가이드를 제공할 수 있다.
- styled-components를 활용한 유용하고 다양한 예제를 기록해두는 공간으로 활용한다.
styled-components
styled-component는 스타일 값으로 함수를 전달할 수 있기 때문에, 기존 HTML/CSS 처럼 새로운 클래스를 추가하는 것이 아니라 prop 값을 기반으로 스타일을 적용할 수 있다. 이는 코드량을 크게 줄일 수 있으이며, styled-component 처음 도입 시, 드라마틱한 향상을 기대할 수 있다고 한다.
🔥 styled-components 스타터 가이드
⒈ 패키지 설치
styled-components를 사용하기 위해 아래의 패키지를 설치해야 한다. (with npm)
npm install --save styled-components
정상적으로 설치되었다면 앱에서 바로 사용할 수 있다! (추가적인 빌드 필요 없음 👌)
NOTE
It's recommended (but not required) to also use the styled-components Babel plugin if you can. It offers many benefits like more legible class names, server-side rendering compatibility, smaller bundles, and more.
공식 페이지에 따르면, Babel 플러그인 사용을 권장하고 있는 만큼 Babel을 함께 도입하는 것이 좋다.
2. 애플리케이션에 적용하기
import styled from 'styled-components' // <Buttom /> const Button = styled.button`` // <BgOpacityBlack /> const BgOpacityBlack = styled.div` background: linear-gradient( 180deg, rgba(39, 63, 40, 0) 0%, rgba(89, 89, 89, 0.558824) 15.62%, #000000 70.83% ); border-radius: 0px 0px 10px 10px; `;
😍 styled-components 기본 예제
1. 용도별 버튼 만들기
다음 예제는 공식 페이지에서 제공하는 예제인데, 간단하지만 파워풀하다!!
const Button = styled.button` background: transparent; border-radius: 3px; border: 2px solid palevioletred; color: palevioletred; margin: 0.5em 1em; padding: 0.25em 1em; ${props => props.primary && css` background: palevioletred; color: white; `} `; const Container = styled.div` text-align: center; ` render( <Container> <Button>Normal Button</Button> <Button primary>Primary Button</Button> </Container> );

styled-components 유용한 예제
Nested structure with styled-component
다음과 같은 Layout에 대해 계층 구조로 스타일 컴포넌트를 작성했다고 가정해보자.
import styled from "styled-components"; function App() { return ( <Layout> <LayoutHeader> Head </LayoutHeader> <LayoutContent> The main body <LayoutContentLeft> Left side of main body </LayoutContentLeft> <LayoutContentRight> The right side of the main body </LayoutContentRight> </LayoutContent> <LayoutFooter> The tail </LayoutFooter> </Layout> ); } const Layout = styled.div``; const LayoutHeader = styled.div``; const LayoutContent = styled.div``; const LayoutContentLeft = styled.div``; const LayoutContentRight = styled.div``; const LayoutFooter = styled.div``;
비교적 간단한 계층 구조로 보이나, 더 깊어지고 복잡해진다면, 컴포넌트에 대한 이름이 길어질 것이고 이는 구조를 파악하기 더 어려워질 것이다.
더 깊어질 계층 구조에 대해 효율적으로 대응할 방법은 없을까?
개선하고자 하는 방식은 아래와 같다.
import styled from "styled-components"; import Layout from "styles/Layout"; function App() { return ( <Layout> <Layout.Header> Head </Layout.Header> <Layout.Content> The main body <Layout.Content.Left> Left side of main body </Layout.Content.Left> <Layout.Content.Right> The right side of the main body </Layout.Content.Right> </Layout.Content> <Layout.Footer> The tail </Layout.Footer> </Layout> ); }
이 방식도 복잡해 보일 수 있으나, 계층 구조를 명확히 표현이 가능하다. Layout.Content.Left와 Layout.Footer.Left간의 컴포넌트 이름이 겹칠 가능성이 크게 줄어들며, 스타일을 계층적으로 표현할 수 있다는 점도 큰 장점이다.
이에 대한 구현 방법은 다음의 링크를 참고해보자.
Structuring our Styled Components | Part I | by Alan B Smith | Medium
Structuring our Styled Components | Part I
How we organize our applications at Decisiv
alanbsmith.medium.com
출처
- styled-components, styled-components Docs, 2022-03-02
- styled components - Production Patterns, Jamie Dixon, 2016-11-02
- Structuring our Styled Components - Part I, Alan B Smith, 2017-12-09
- Structuring our Styled Components - Part II, Alan B Smith, 2018-08-06
- Let styled components also have a hierarchy, tellyourmad, 2022-03-23
Last Updated. 2022. 08. 26.
블로그의 정보
배부른코딩로그
배부른코딩로그