학습목표



CSS in JS

: style 정의를 CSS 파일이 아닌!! JS로 작성된 컴포넌트에 삽입하는 기법

Styled Components

사용 방법

props 사용하기

: React 컴포넌트에 넘어온 props를 사용하여 가변 스타일링

  1. 첫번째 방법

    import React from "react";
    import styled from "styled-components";
    
    const StyledButton = styled.button`
      padding: 6px 12px;
      border-radius: 8px;
      font-size: 1rem;
      line-height: 1.5;
      border: 1px solid lightgray;
    
      color: ${(props) => props.color || "gray"};
      background: ${(props) => props.background || "white"};
    `;
    
    function Button({ children, color, background }) {
      return (
        <StyledButton color={color} background={background}>
          {children}
        </StyledButton>
      );
    }
    
  2. 두번째 방법

    import React from "react";
    import styled, { css } from "styled-components";
    
    const StyledButton = styled.button`
      padding: 6px 12px;
      border-radius: 8px;
      font-size: 1rem;
      line-height: 1.5;
      border: 1px solid lightgray;
    
      ${(props) =>
        props.primary &&
        css`
          color: white;
          background: navy;
          border-color: navy;
        `}
    `;
    
    function Button({ children, ...props }) {
      return <StyledButton {...props}>{children}</StyledButton>;
    }
    

사용하는 이유