styled component 사용방법

kiseon·2024년 8월 6일
0

TIL

목록 보기
11/26
post-thumbnail


styled component 공식

styled component 시작

  1. styled-components설치
npm install --save styled-components
  1. styled-components를 사용하는 곳에서 불러오기
import styled from 'styled-components';

styled component 사용

선언

const 식별자 = styled.태그

사용

<식별자>
...
</식별자>

예시

import styled from 'styled-components';

const StyledSection = styled.section`
  ${flex(undefined, "center", "center", "20px", "wrap")}
  padding: 20px 40px;
`;

function App() {
  return (
      <StyledSection>
        {contents.map((el) => (
          <Content key={el.id} content={el} />
        ))}
      </StyledSection>
  );
}

export default App;

styled component 변수

선언

export const 식별자 = 내용;

사용

css속성: ${식별자};

예시

export const gray = "rgb(160, 160, 160)";
import { gray } from "../../styled/color";

const StyledContent = styled.div`
    color: ${gray};
`;

styled component 함수

선언

import { css } from "styled-components";

export const 함수이름 = (
	키 = "값"
) => {
  return css`
  	속성 : 키;
  `;
};

사용

${함수이름()};
${함수이름("값")};

예시

import { css } from "styled-components";

export const flex = (
  direction = "row",
  justify = "start",
  align = "stretch",
  gap = "0",
  wrap = "nowrap"
) => {
  return css`
    display: flex;
    flex-direction: ${direction};
    justify-content: ${justify};
    align-items: ${align};
    gap: ${gap};
    flex-wrap: ${wrap};
  `;
};

const StyledHeader = styled.header`
  ${flex(undefined, "space-between", "center")}
  padding: 20px 20px;
  background-color: black;
  ul {
    ${flex(undefined, "center", "center", "20px")}
    li {
      ${font(undefined, 400)}
      list-style: none;
    }
  }
`;   

Global style

선언

import { createGlobalStyle } from "styled-components";

const GlobalStyle = createGlobalStyle`
...
`;

export default GlobalStyle;

사용

import GlobalStyle from "./GlobalStyle";

<GlobalStyle />

예시

import { createGlobalStyle } from "styled-components";

const GlobalStyle = createGlobalStyle`
  *, *::before, *::after {
    margin: 0;
    padding: 0;
    box-sizing: border-box;
    color: white;
  }

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

export default GlobalStyle;

import Content from "./components/Content";
import GlobalStyle from "./GlobalStyle";

function App() {
  return (
      <GlobalStyle />
  );
}

export default App;
profile
되고싶다.. 개발자..!

1개의 댓글

comment-user-thumbnail
2024년 8월 6일

예시도 있고 보기 편하게 정리가 잘되어 있네요

답글 달기