React - Styled component 시작하기

Moolbum·2021년 12월 15일
0

Styled-components

목록 보기
1/5
post-thumbnail

Style Component

리액트에서 스타일을 줄 수 있는 방법이 더 있다.
Style Component 를 사용 하는 방법이다!

SASS도 좋았지만 Style Component 를 사용하는 이유가 있다.

  • 클래스 이름의 중첩을 줄여줌
  • attribute 추가가 가능
  • 스타일에 props를 적용 할 수 있다
  • SASS 처럼 mixin 이 가능

컴포넌트 자체로 사용하기 때문에 더욱 직관적으로 코드를 볼 수 있습니다.

설치방법
npm install --save styled-components

사용방법

  • 상단에 import를 해준다
  • 컴포넌트 생성
  • 하단에 styled와 태그를 선언
import styled from 'styled-components';

const PriceButton = () => {
return(
   <PriceWrap>
      <Percent>10%</Percent>
      <Price>월 10000원</Price>
   </PriceWrap>
  )
}

const PriceWrap = styled.div`
  display: flex;
  align-items: flex-end;
`;

theme 사용방법

공통으로 사용될 theme.js 를 생성!

const theme = {
  black: '#000',
  darkGray: '#666',
  gray: '#a2a2a2',
  mediumGray: '#e5e5e5',
  lightGray: '#f8f8f8',
  white: '#fff',
  red: '#fd3049',
  orange: '#ff5600',
  puple: '#6300d8',
  green: '#84bd00',
  blue: '#004ec3',

  fontExtraLarge: '34px',
  fontLarge: '24px',
  fontMedium: '18px',
  fontSemiMedium: '16px',
  fontRegular: '14px',
  fontSmall: '13px',
  fontMicro: '11px',

  weightBold: '700',
  weightSemiBold: '500',
  weightRegular: '400',
  weightThin: '300',

  borderRadius4: '4px',
  borderRadius12: '12px',

  borderGray: '1px solid #e8e8e8',
  borderBlack: '1px solid #000',

  marginCenter: '0 auto',

  flex: (direction = 'row', align = 'center', justify = 'center') => `
    display: flex;
    flex-direction: ${direction};
    align-items: ${align};
    justify-content:${justify};
    `,

  absoluteCenter: `
    position: absolute;
    top: 50%;
    left: 50%;
    transform: translate(-50%, -50%);
    `,

  positionFixed: `
    position: fixed;
    top: 0;
    left: 0;
    z-index:999;
  `,
};

export default theme;

스타일 컴포넌트에 ${props => props.theme. (mixin)} 를 입력해주면 됩니다!

flex 사용
const PriceContainer = styled.div`
  ${props => props.theme.flex('row', 'center', 'space-between')};
`;

폰트사이즈 및 두께변경
const Title = styled.h1`
  margin-bottom: 10px;
  font-size: ${props => props.theme.fontMedium};
  font-weight: ${props => props.theme.weightBold};
  line-height: 25px;
`;

네스팅

SASS처럼 네스팅도 가능!

const Nav = styled.div`
  font-size: 10px;

  &:hover {
    font-size: 12px;
    color: red;
  }
`;

attrs

태그들의 속성까지 스타일 컴포넌트에서 적용이 가능하다!

const CommentInput = styled.input.attrs({
  type: `text`,
  placeholder: `댓글을 입력해주세요.`,
})`
`width:100%;
.
.
`;
profile
Junior Front-End Developer 👨‍💻

0개의 댓글