aotoyae

[React] styled components CSS, createGlobalStyle 본문

React

[React] styled components CSS, createGlobalStyle

aotoyae 2024. 1. 24. 15:28

 

 

💅 스타일드 컴포넌트를 사용해보자

먼저 styled components 플러그인을 설치하고,

터미널에 npm add styled-components 를 입력한다.

그럼 세팅 끝!

 

import "./App.css";
import styled from "styled-components"; {/*style 를 임포트 해온다.*/}

const StContainer = styled.div` {/*div 에 스타일 적용*/}
  display: flex;
`;

const StBodx = styled.div`
  width: 100px;
  height: 100px;
  border: 1px solid ${(props) => props.borderColor}; {/*props 를 받아올 수 있음*/}
  margin: 10px;
`;

const boxList = ["red", "blue", "green", "black"];

const getBoxName = (color) => { {/*switch 로 컬러마다 다른 값 리턴*/}
  switch (color) {
    case "red":
      return "RED BOX";
    case "blue":
      return "BLUE BOX";
    case "green":
      return "GREEN BOX";
    default:
      return "BLACK BOX";
  }
};

function App() {
  return (
    <StContainer> {/*적용한 스타일의 블럭 div 처럼 작성*/}
      {boxList.map((box) => ( {/*map 을 활용해 각각 다른 이름과 컬러의 박스를 출력*/}
        <StBodx key={box} borderColor={box}>
          {getBoxName(box)}
        </StBodx>
      ))}
    </StContainer>
  );
}

export default App;

 

css를 자바스크립트처럼 활용할 수 있다! 👀

 

 

🚨 props 내려줄 때 주의

const StBtn = styled.button`
  ${(props) => {
    if (props.$activeMember === props.children) {
      return css`
        background: red;
        color: #fff;
      `;
    }
  }}
`;

// .......
<StBtn $activeMember={activeMember} onClick={onActiveMember}>
  {member.id}
</StBtn>

 

태그에서 props 를 내려줄 때 카멜케이스로 쓰면 앞에 달러 표시 $ 를 붙여주어야 한다!

 

 

💅 GlobalStyles 전역 스타일링 적용

App.jsx

import "./App.css";
import GlobalStyle from "./GlobalStyle";
import TestPage from "./components/TestPage";

function App() {
  return (
    <>
      <GlobalStyle /> {/*전역 스타일을 가져온다.*/}
      <TestPage title="title" contents="content" />
    </>
  );
}

export default App;

 

TestPage.jsx

import styled from "styled-components";

function TestPage(props) {
  return (
    <Wrapper>
      <Title>{props.title}</Title>
      <Contents>{props.contents}</Contents>
    </Wrapper>
  );
}

const Title = styled.h1`
  font-size: 1.5rem;
  margin: 0;
  margin-bottom: 8px;
`;

const Contents = styled.p`
  margin: 0;
  font-size: 1rem;
`;

const Wrapper = styled.div`
  border: 1px solid black;
  border-radius: 8px;
  padding: 20px;
  margin: 16px auto;
  max-width: 400px;
`;

export default TestPage;

 

GlobalStyle.jsx

import { createGlobalStyle } from "styled-components";

const GlobalStyle = createGlobalStyle`
  body{
    font-family: "Helvetica", "Arial", sans-serif;
    line-height: 1.5;
  }
`;

export default GlobalStyle;

 

TestPage 에 있는 title, content, wrapper(body 아래 요소들 모두) 에 모두 스타일링이 적용된다.

 

🚨 Link 태그 스타일 적용법

적용이 안되어서 그냥 태그에 style 을 넣어주고 있었는데

작성법이 따로 있었다!

const StLink = styled(Link)`
  text-decoration: none;
`;