react.js styled-components 예제로 보는 적용방법

조민혜·2022년 11월 3일
0

React.js

목록 보기
5/12

적용하는 방법만 기술 할테지만 'CSS in JS' 라는 개념을 한번 찾아 보고 어떤 방식인지 한번 공부해보는걸 추천합니다.

< styled-components 설치 >

npm i styled-components

< styled-components 적용 예제 >

  • import styled from "styled-components";

1. 컴포넌트내 다중 사용

import React, { useEffect } from "react";
import styled from "styled-components";

export const Header = (props) => {
  return (
    <>
      <HeaderDiv>
        <ContentDiv>
          <ServiceTitle> Title </ServiceTitle>
        </ContentDiv>
      </HeaderDiv>
    </>
  );
};

const HeaderDiv = styled.div`
  font-family: NotoSansCJKkr;
  font-size: 12px;
  height: 56px;
  display: flex;
  align-items: center;
`;

const ServiceTitle = styled.div`
  margin-left: 24px;
  font-family: Helvetica;
  font-size: 18px;
  font-weight: bold;
`;

const ContentDiv = styled.div`
  display: flex;
`;

2. 스타일만 사용

import styled from "styled-components";

const Hr = styled.hr`
  width: 100%;
  margin: 0px;
  border-top: 1px;
`;

export default Hr;

3. styled-components에서 props 사용

// 예제 1
<ExDiv2 size="12px">margin-right div</ExDiv2>

const ExDiv1 = styled.input.attrs((props) => ({
  type: "text",
  size: props.size || "1em",
}))`
  border: 2px solid palevioletred;
  margin: ${(props) => props.size};
  padding: ${(props) => props.size};
`;

// 예제2 
<ExDiv2 mr="8px">margin-right div</ExDiv2>
<ExDiv2 ml="8px">margin-left div</ExDiv2>

const ExDiv2 = styled.div`
  margin-top: 5px;
  font-weight: 300;
  ${(props) =>
    ` margin-right: ${props.mr || "0px"};
      margin-left: ${props.ml || "0px"};
    `};
`;

대략 위 처럼 작성 하게 되는데
주의할점은 styled-components 로 작성된 변수들이 (HeaderDiv, ServiceTitle, ContentDiv) export / return 문 바깥으로 정의 되어야 한다.

profile
Currently diving deeper into React.js development.

0개의 댓글