☁️ goormTIL | React #25

매루·2025년 10월 15일

goormTIL

목록 보기
23/67
post-thumbnail

📅 2025-10-25

➡️ React styled-components에 대해 새롭게 알게 된 것 또는 헷갈리는 부분 정리 + 🤔❓


🔎 학습 리마인드

📌 styled-components

💡 CSS-in-JS란?

  • CSS를 자바스크립트 코드 안에서 작성하는 것
  • 조건문, 변수, 함수 같은 로직을 활용해서 훨씬 유연하게 스타일을 제어할 수 있음

💡 styled-components란?

🔗 https://styled-components.com/

  • CSS-in-JS방식을 구현해주는 대표적인 라이브러리
  • 설치
    npm i styled-components
  • 사용법
    ```jsx
    import React from "react";
    
    import styled from "styled-components";
    
    const Box = styled.div`
      width: 100px;
      height: 100px;
      border: 2px solid tomato;
      margin: 20px;
    `;
    
    function App() {
      return <Box>박스</Box>;
    }
    
    export default App;
    ```
    
    - ```백틱(`)``` 안에 CSS 문법을 그대로 작성할 수 있고, 만든 컴포넌트를 JSX에서 `<Box />`처럼 사용할 수 있음
    - `styled.`  뒤에는 html의 태그가 옴. html 태그를 사용해서 styled-components를 만들 수 있음

💡 조건부 스타일링

import styled from "styled-components";

const Box = styled.div`
  width: 100px;
  height: 100px;
  border: 2px solid ${(props) => props.color};
  margin: 20px;
`;

function App() {
  return (
    <div>
      <Box color="red">빨강</Box>
      <Box color="green">초록</Box>
      <Box color="blue">파랑</Box>
    </div>
  );
}

export default App;

💡 전역 스타일링

  • createGlobalStyle 사용
    // GlobalStyle.jsx
    import { createGlobalStyle } from "styled-components";
    
    const GlobalStyle = createGlobalStyle`
      body {
        font-family: "Arial", sans-serif;
        line-height: 1.5;
      }
    `;
    
    export default GlobalStyle;
    // App.jsx
    import GlobalStyle from "./GlobalStyle";
    
    function App() {
      return (
        <>
          <GlobalStyle />
          <p>전역 스타일이 적용된 텍스트</p>
        </>
      );

🌊 Deep Dive

🤔 Styled-Component : $prefix (Transient Props)

  • ⚠️ 스타일드 컴포넌트에 props를 전달할 때, 이 props가 실제 DOM 요소로 전달되면 아래와 같은 경고가 발생할 수 있음
    styled-components: it looks like an unknown prop "isClicked" is being sent through to the DOM, which will likely trigger a React console error. If you would like automatic filtering of unknown props, you can opt-into that behavior via `<StyleSheetManager shouldForwardProp={...}>` (connect an API like `@emotion/is-prop-valid`) or consider using transient props (`$` prefix for automatic filtering.)
    • "isClicked" 같은 props가 DOM 요소로 전달되어서는 안 된다는 의미
    • 해결 방법
      1. shouldForwardProp 옵션을 직접 설정하거나
      2. $ prefix (Transient Props)를 사용하여 자동으로 필터링되게 하기

$ prefix란?

  • $를 props 앞에 붙이면, 해당 props는 styled-components 내부에서만 사용되고 실제 DOM으로 전달되지 않음
    const Button = styled.button`
      background-color: ${(props) => (props.$isClicked ? 'blue' : 'gray')};
    `;
    
    <Button $isClicked={true}>버튼</Button>
  • 얘는 다른데선 안 쓰고 스타일드 컴포넌트에서만 씁니다라고 명시하는 것!!!

🔗 https://styled-components.com/docs/api?utm_source=chatgpt.com#transient-props

🔗 https://velog.io/@cmk0905/Styled-Component-prefix


0개의 댓글