Web/React

React - Styled Components 01

또롱또 2022. 5. 16. 17:18
728x90

장점

  • 페이지에서 렌더링되는 요소에 맞춰 자동으로 해당 스타일만 삽입합니다. 그때그때 필요한 스타일만 로드한다는 거죠!
  • 스타일에 대한 고유 클래스명을 생성합니다. 중복이나 오타 걱정 노놉
  • 더이상 사용되지 않는 CSS를 쉽게 삭제할 수 있습니다. 모든 스타일은 특정 요소와 연결되어 있기 때문에 해당 요소가 삭제되면 스타일도 삭제돼요.
  • 동적 스타일링이 편해집니다. 이 props가 있다면 A, 없다면 B와 같이 직관적으로 개별 스타일링이 가능해요.

출처: https://nykim.work/107

npm install styled-components

TIP. styled-components 내에서 emmet을 쓰고 싶다면 vscode-styled-components 을 설치

 

1. Styled Components 문법

일단 import를 해주고 

아래 코드처럼, 함수밖에서 컴포넌트처럼 만들어서 쓸수있다.

문법순서는 const 컴포넌트이름 = import할때쓴이름.tag이름 `` 이다.

import { useEffect, useRef, useState } from "react";
import styled from 'styled-components'

const App = () => {

  return (
    <Container>
       <h1>THIS IS TITLE</h1>
    // props를 부를땐 이렇게 부른다
      <Button danger>BUTTON</Button>
      <Button >BUTTON</Button>
    </Container>
  );
}


const Container = styled.div`
  width: 100%;
  height: 100vh;
  background-color: #f6e58d
  // 이 태그 안에있는 다른 태그에 접근
  h1{
    color: #3B3B98
  }
`;


const Button = styled.button`
  min-width: 120px;
  border-radius:50px;
  padding: 5px;
  color: white;
  cursor: pointer;
  -webkit-appearance: none;
  // Props 사용은 아래와 같이했다
  background-color: ${props => props.danger? "#e74c3c" : "#2ecc71"}
`;


export default App;

 

 

2. Extend

만약에 원래 정의한 컴포넌트의 CSS를 SASS처럼 extend 하고싶으면

아래처럼 정의하면 된다.

// () 이 괄호안에 extend할 컴포넌트 이름
const ExtendButton = styled(Button)`
  // props 한개만 쓰면 이렇게 쓸 수 있다.
  background-color: ${props => props.extended || "#45aaf2"};
`;


//대신 컴포넌트 이름도 변경됌
<ExtendButton>BUTTON</ExtendButton>

 

그리고 만약에 스타일만 가져오는데 태그를 변경하고 싶을때는

as 속성을 이용한다. 아래 예제처럼 as만 이용하면 뒤에 속성은 추가 가능.

대신 as를 쓰면 더이상 버튼으로는 인식이 안된다 - a tag로 인식된다. inspection 시

<ExtendButton as="a" href="https://google.com" >A TAG </ExtendButton>

 

3. 애니메이션 적용하기

일단은 keyframes를 import 해야한다.

import styled, { keyframes } from 'styled-components'

아래처럼 사용하면 된다.

*선언이 호출보다 위에있어야한다.

const animation = keyframes`
  50% {
    transform: scale(1.3);
  }
`;

const ExtendButton = styled(Button)`
  background-color: ${props => props.extended || "#45aaf2"};
  animation: ${animation} 1s infinite;
`;

 

 

4. `` 백틱에 대해서

템플릿 리터럴 이라고 부르고,

런타임 시점에 자바스크립트 문자열로 변경된다.

https://developer.mozilla.org/ko/docs/Web/JavaScript/Reference/Template_literals

 

 

5. 공용 CSS 

* 태그나 body 이런건 공용으로 관리해 주는게 좋다.

모든 페이지에 적용시켜야 하니까.

아래처럼 createGlobalStyle 을 이용하면 된다.

공용 css는 따로 빼주는게 좋다.

/* GlobalStyle.js */
import { createGlobalStyle} from 'styled-components';

const GlobalStyle = createGlobalStyle `
* {
    margin: 0;
    padding: 0;
}

body {
    background-color: #000000;
}
`;

export default GlobalStyle;

그리고 모든 페이지에 넣을거니까

최상단 페이지인 index.js 에서 부르면 된다.

import React from 'react';
import ReactDOM from 'react-dom/client';
import App from './App';
import reportWebVitals from './reportWebVitals';
import GlobalStyle from "./GlobalStyle";

const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(
  <React.StrictMode>
  // 이렇게 부른다
    <GlobalStyle />
    <App />
  </React.StrictMode>
);

reportWebVitals();

 

6. Normalize

웹브라우저마다 기본적으로 적용되어있는 스타일을 지워주는 용도의 css 파일

reset.css 하고 같다고 보면 된다.

설치

npm i styled-normalize

공용css에 같이 처리해주면 좋다.

사용법

/* GlobalStyle.js */
import { createGlobalStyle} from 'styled-components';
import { normalize } from "styled-normalize";

const GlobalStyle = createGlobalStyle `
// 이렇게 호출한다
${normalize}
* {
    margin: 0;
    padding: 0;
}

body {
    background-color: #000000;
}
`;

export default GlobalStyle;
728x90