
styled component 공식
styled component 시작
- styled-components설치
npm install --save styled-components
- 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;
예시도 있고 보기 편하게 정리가 잘되어 있네요