본문 바로가기

Front-end/React

Styled-component

정의


css-in-js 라이브러리:스타일 정의를 css 파일이 아닌 js로 작성된 컴포넌트에 바로 삽입하는 스타일 기법

 

 

Tagged Template Literal


Template Literal - ES6 문법
const name = 'react';
const message = `hello ${name}`;

console.log(message);
// "hello react"

const object = { a: 1 };
const text = `${object}`
console.log(text);
// "[object Object]"

const fn = () => true
const msg = `${fn}`;
console.log(msg);
// "() => true" 함수 선언부를 그대로 리턴

const red = '빨간색';
const blue = '파란색';

// 가변인자들을 하나의 배열에 할당하는 rest문법사용
function favoriteColors(texts, ...values) {
  console.log(texts);
  console.log(values);
}
favoriteColors`제가 좋아하는 색은 ${red}과 ${blue}입니다.`
 styled-component에서도 template literal 문법을 사용하여 컴포넌트의 props를 읽어오고 있음

 

특징

  • js 로 삽입된 css 코드는 global name-space를 사용하지 않음
    • -> js 파일마다 고유한 css name-space를 부여해주기 때문에, 각 컴포넌트에서 완전히 격리된 style 적용 가능

 

사용하기


기본 스타일링

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

const Circle = styled.div`
  width: 5rem;
  height: 5rem;
  background: black;
  border-radius: 50%;
`;

function App() {
  return <Circle />;
}

export default App;

 

props

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

// props color를 사용해 동적으로 스타일 적용
const Circle = styled.div`
  width: 5rem;
  height: 5rem;
  background: ${props => props.color || 'black'};
  border-radius: 50%;
`;

function App() {
  return <Circle color="blue" />;
}

export default App;

 

css func

  • 여러줄의 css 코드를 조건부로 사용하는 경우
import React from 'react';
import styled, { css } from 'styled-components';

// css 함수를 이용해 동적으로 여러줄의 css 코드 적용
const Circle = styled.div`
  width: 5rem;
  height: 5rem;
  background: ${props => props.color || 'black'};
  border-radius: 50%;
  ${props =>
    props.huge &&
    css`
      width: 10rem;
      height: 10rem;
    `}
`;

function App() {
  return <Circle color="red" huge />;
}

export default App;

 

ThemeProverder

모든 하위 컴포넌트에서 조회하여 사용할 수 있는 global variable 을 설정
function App() {
  return (
    <ThemeProvider
      theme={{
        palette: {
          blue: '#228be6',
          gray: '#495057',
          pink: '#f06595'
        }
      }}
    >
      <AppBlock>
        <Button>BUTTON</Button>
      </AppBlock>
    </ThemeProvider>
  );
}

export default App;

// Button.js
const StyledButton = styled.button`
  ...

  ${props => {
    const selected = props.theme.palette.blue;
    return css`
      background: ${selected};
      &:hover {
        background: ${lighten(0.1, selected)};
      }
      &:active {
        background: ${darken(0.1, selected)};
      }
    `;
  }}

 

주의)
custom component의 경우 className 을 전달해주어야 상속됨

ex)
const MyComponent = ({ className }) =>{
  return <div className={className}></div>
};
const ExtendedComponent = styled(MyComponent)`
  background: black;
`;

 

 

 

참고자료

https://www.daleseo.com/react-styled-components/

 

Styled Components로 React 컴포넌트 스타일하기

Engineering Blog by Dale Seo

www.daleseo.com

https://react.vlpt.us/styling/03-styled-components.html

 

3. styled-components · GitBook

03. styled-components 이번에 배워볼 기술은 CSS in JS 라는 기술입니다. 이 문구가 뜻하는 그대로, 이 기술은 JS 안에 CSS 를 작성하는 것을 의미하는데요, 우리는 이번 튜토리얼에서 해당 기술을 사용하

react.vlpt.us

 

'Front-end > React' 카테고리의 다른 글

useRef & Refs  (0) 2023.01.30
Next  (0) 2023.01.10
React Query  (0) 2022.11.28
Redux  (0) 2022.11.23
Hook  (0) 2022.11.23