styled-components는 기존에 css, scss 파일을 밖에 두고 태그나 id, class이름으로 가져와 쓰는 스타일 지정 방식에서 벗어나, js 파일 내에서 컴포넌트 이름을 쓰듯 스타일을 지정하는 react 라이브러리다. css 파일을 따로 만드는 번거러움을 없앴고, 컴포넌트만 입력하면 class name을 자동으로 부여하기 때문에 css가 전역으로 중첩되지 않도록 만들어주는 장점이 있다.
styled-components는 npm 명령어로 설치할 수 있다.
npm i styled-components
import styled from "styled-components";
example)
const Box = styled.div`
background-color: tomato;
width: 100px;
height: 100px;
`;
function App() {
return (
<Box>
<span>Hello</span>
</Box>
)}
const Circle = styled(Box)`
border-radius: 50px;
background-color: ${(props) => props.bgColor};
`;
function App() {
return (
<Circle bgColor="whitesmoke">
<span>Hello</span>
</Circle>
)}
const Input = styled.input.attrs({ required: true, maxLength: 10 })`
background-color: tomato;
`;
<Box as="main">
<span>Hello</span>
</Box>
import {keyframes} from "styled-components";
const animation = keyframes`
0% {
transform: rotateZ(0deg);
border-radius: 0px;
}
50% {
transform: rotateZ(180deg);
border-radius: 25px;
}
100% {
transform: rotateZ(360deg);
border-radius: 50px;
}
`;
const Box = styled.div`
width: 100px;
height: 100px;
animation: ${animation} 1s linear infinite;
`;
모든 style component들은 export하여 다른 파일에서 재사용 가능하다.
import { ThemeProvider } from "styled-components";
const darkTheme = {
textColor: "whitesmoke",
backgroundColor: "black",
};
const lightTheme = {
textColor: "black",
backgroundColor: "whitesmoke",
};
const root = ReactDOM.createRoot(document.getElementById("root"));
root.render(
<ThemeProvider theme={darkTheme}>
<App />
</ThemeProvider>
);
const Circle = styled(Box)`
border-radius: 50px;
background-color: ${(props) => props.theme.backgroundColor};
`;
styled.d.ts
import "styled-components";
declare module "styled-components" {
export interface DefaultTheme {
red: string;
black: {
veryDark: string;
darker: string;
lighter: string;
};
white: {
darker: string;
lighter: string;
};
}
}
theme.ts
import { DefaultTheme } from "styled-components";
export const theme: DefaultTheme = {
red: "#E51013",
black: {
veryDark: "#141414",
darker: "#181818",
lighter: "#2F2F2F",
},
white: {
lighter: "#fff",
darker: "#e5e5e5",
},
};