React

CSS in JS : styled-components

일단두잇 2023. 1. 20. 16:48
반응형

https://styled-components.com/

 

 

1. styled-components 사용하기전에 Template Literal에 대해 먼저 알아야 한다.

const name = 'template literal';
const message = `string text ${name}`;
console.log(message);
//string text template literal
 

간단히 말해서 string에 변수를 조합해서 사용하는 방식이다.

 

이것이 필요한 이유는 CSS를 string 형태로 정의해서 사용하기 때문이다.

이렇게 쓰지 않는다면 엄청나게 길어지는 string + 를 보게 될것이다...

 

2. Styled-components Library 설치

npm install styled-components
 

3. styled-components 생성

 

  • 하위 클래스 까지 정의가 가능
  • css를 그대로 활용 가능
  • scss 문법 사용 가능
import styled from 'styled-components';

const Container = styled('div')`
  .title {
    text-align: center;
    color: #000;
    font-weight: 700;
    font-size: 1.5rem;
    margin-bottom: 40px;
    margin-top: 20px;
    display: inline-flex;
    width: 100%;
    margin-left: 25px;

    // 하위클래스 정의
    &-label {
      width: 100%;
      text-align: center;
    }
  }

  .content {
    text-align: center;
  }
`;

const RoundButton = styled('button')`
  height: 40px;
  color: #000;
  padding: 10px;
  padding-left: 20px;
  padding-right: 20px;

  &.selected {
    color: #fff;
    padding-left: 30px;
    padding-right: 30px;
    border-radius: 2.2rem;
    background-color: #0064de;
  }
`;

const CssStylePage = () => {
  return (
    <Container>
      <div className="title">
        <label className="title-label">styled-components</label>
      </div>
      <div className="content">
        <ul>
          <li>
            <RoundButton>버튼1</RoundButton>
            <RoundButton className="selected">버튼2</RoundButton>
          </li>
        </ul>
      </div>
      <div className="bg"></div>
    </Container>
  );
};
export default CssStylePage;
 

 

  • 스타일을 상속해서 생성
const PrimaryButton = styled('button')`
  height: 40px;
  color: #000;
  padding: 10px;
  padding-left: 20px;
  padding-right: 20px;

  &.selected {
    color: #fff;
    padding-left: 30px;
    padding-right: 30px;
    border-radius: 2.2rem;
    background-color: #0064de;
  }
`;

// PrimaryButton 스타일을 상속하여 새로운 스타일을 적용
const RoundButton = styled(PrimaryButton)`
  border-radius: 2.2rem;
`;
 

 

 

반응형