📅 2025-10-25
➡️ React 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>
</>
);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 요소로 전달되어서는 안 된다는 의미shouldForwardProp 옵션을 직접 설정하거나$ 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