[TIL] Styled-Componets

kiyeol·2021년 2월 7일
0

오랜만에 프로젝트 1차가 끝나고 나서.. 2차 준비하고 발표하면서 바쁜 나머지 velog를 정리하지 못한것을 정리해보려고 한다.

오늘은 리액트에서 가장 인기 있는 라이브러리로 css in js인 styled componets 라이브러리에 대해서 포스팅 해보려고 한다.

스타일드 컴포넌트는 스타일을 바로 컴포넌트를 만들어낼 수 있고, 자바스크립트 파일 안에 스타일을 지정할 수 있다.

styled-componets install

스타일드 컴포넌트를 사용하려면 다음과 같이 설치 할 수 있다.

npm install --save styled-components

vscode 내부에서 색상 지원 및 자동완성을 쓰려면 vscode-styled-components 설치 받으면 된다.

styled-componets manual

첫번째로 import를 버튼을 스타일드 컴포넌트로 만드는 예제이다.

import styled from 'styled-components'

const Button = styled.button`
  background: transparent;
  border-radius: 3px;
  border: 2px solid palevioletred;
  color: palevioletred;
  margin: 0 1em;
  padding: 0.25em 1em;
`

이런식으로 Template Literals을 이용해서 안에 스타일을 자기 마음대로 지정할 수 있다.

두번째로는 props를 전달 받아서 스타일드 컴포넌트를 사용할 수 있다.
primary라는 props를 사용할 때, css를 지정해 주는 코드이다.

const Button = styled.button`

  ${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>
);

세번째로 nesting , Mixin 및 Attaching additional props 속성 부여가 가능하다.

sass에 기능중 하나인 CSS selector(선택자)를 다른 selector의 스코프에 포함시키는 것을 그대로 사용할 수 있다. (코드 중복 및 DOM 관계를 명확하게 할 수 있다.)

.parent {
  color: blue;
  .child {
    font-size: 12px;
  }
}

scss에서 사용했던 mixin 기능과 attrs라는 속성을 이용해 사용해서 고정되는 Props를 전달해서 사용할 수 있다.

const button = css`
  border: 2px solid black;
  font-size: 20px;
`;

const Navigation = styled.nav`
  position: fixed;
  left: 0;
  top: 0;
  right: 0;
  ${button}
`;
const Input = styled.input.attrs(props => ({
  type: "password",
  size: props.size || "1em",
}))`

마지막으로 Global Style & ThemeProvider을 이용할 수 있는데, styled 컴포넌트를 reset 하려면 다음과 같이 npm install을 해서 설치 및 import를 해서 전역스타일을 지정할 수 있다.

npm install --save styled-components styled-reset

const GlobalStyle = createGlobalStyle`
  ${reset}
  /* other styles */
    * {
      box-sizing:boerder-box;
    }

ThemeProvider 기능은 감싸진 자식 컴포넌트(Component)들은 ThemeProvider로 전달받은 theme를 props로 전달받아서 사용할 수 있다.

import React from "react";
import styled, { createGlobalStyle, ThemeProvider } from 'styled-components';
import themes from './themes';

const App = () => {
  return (
    <div>
      <ThemeProvider theme={theme}>
        <Navbar />
        <Search />
      </ThemeProvider>
    </div>
  );
};

[ themes.js ]


const themes = {
  redColor: 'red',
  grayColor: 'gray',
  blueColor: 'blue',
}
export default themes;
     
const Button = styled.button`
  border-radius: 30px;
  padding: 25px 15px;
  background-color: ${props => props.theme.blueColor} 
`;

이렇게 전달 받은 theme의 값을 사용할 수 있다.

출처 : https://styled-components.com/docs/basics#getting-started

profile
kyday63@gamil.com

0개의 댓글