티스토리 뷰

dev/React

styled-component

dev_0hoon 2024. 2. 26. 19:31
npm install styled-components

를 입력해서 설치한다.

 

import styled from 'styled-components';

사용하려는 js에 임폴트 한다.

 

만약 이쁜 버튼을 만들고 싶다면?

import { useParams } from "react-router-dom";
import styled from 'styled-components';

let YellowBtn = styled.button`
  background : yellow;
  color : black;
  padding : 10px;
`

let Box = styled.div`
  background : grey;
  padding : 20px;
`

function Detail(props){

  let {id} = useParams();

  console.log(id);

    return (
      <div className="container">
        <Box>
          <YellowBtn>버튼</YellowBtn>
        </Box>
        <div className="row">
          <div className="col-md-6">
            <img src="https://codingapple1.github.io/shop/shoes1.jpg" width="100%" />
          </div>
          <div className="col-md-6">
            <h4 className="pt-5">{props.shoes[id].title}</h4>
            <p>{props.shoes[id].content}</p>
            <p>{props.shoes[id].price}</p>
            <button className="btn btn-danger">주문하기</button> 
          </div>
        </div>
      </div> 
    );
  }

  export default Detail;

 

 

상단에 styled라이브러리를 이용해서 css입력이 가능해진다. 함수로 만들어 태그를 입혀 사용할 수 있음.

 

장점 1. 스타일이 다른 js파일로 오염되지 않음

장점 2. 페이지 로딩시간 단축

 

이게 styled-component의 장점이다. 하지만 사실 이 라이브러리 외에도 css오염을 막는 방법이 있다.

네이밍을 중간에 App.module처럼 module을 붙여주면 App.js에서만 사용되게 된다.

 

 

다시 styled-component로 돌아와서 말하자면 props를 사용하는 방식도 가능하다. 또 이프문도 가능함

import { useParams } from "react-router-dom";
import styled from 'styled-components';

let YellowBtn = styled.button`
  background : ${ props => props.bg};
  color :  ${ props => props.bg == 'blue' ? 'white' : 'black'};
  padding : 10px;
`

let NewBtn = styled.button(YellowBtn)` 복사해버리기
  스타일 넣어서 커스텀마이징 가능
`

function Detail(props){

  let {id} = useParams();

  console.log(id);

    return (
      <div className="container">
        <YellowBtn bg="blue">버튼</YellowBtn>
        <YellowBtn bg="orange">버튼</YellowBtn>
        <div className="row">
          <div className="col-md-6">
            <img src="https://codingapple1.github.io/shop/shoes1.jpg" width="100%" />
          </div>
          <div className="col-md-6">
            <h4 className="pt-5">{props.shoes[id].title}</h4>
            <p>{props.shoes[id].content}</p>
            <p>{props.shoes[id].price}</p>
            <button className="btn btn-danger">주문하기</button> 
          </div>
        </div>
      </div> 
    );
  }

  export default Detail;

 

단점은 js가 길어지면 일반 컴포넌트인지 애매해지고 찾기 어려워진다.

 

 

'dev > React' 카테고리의 다른 글

서버 데이터 요청 (ajax - axios)  (0) 2024.02.29
Lifecycle  (1) 2024.02.26
파라미터 받기  (0) 2024.02.26
리액트 페이지마다 url 나누기 +404만들기  (1) 2024.02.26
import,export  (0) 2024.02.23
공지사항
최근에 올라온 글
최근에 달린 댓글
Total
Today
Yesterday
링크
«   2025/07   »
1 2 3 4 5
6 7 8 9 10 11 12
13 14 15 16 17 18 19
20 21 22 23 24 25 26
27 28 29 30 31
글 보관함