Styled-component

차차·2023년 1월 28일
post-thumbnail

Styled-components 설치

npm i styled-components

기본적인 사용 방법

  • variable = styled.<태그>css
import styled from "styled-components";

const Wrapper = styled.div`
	width:100vw;
	height:100vh;
	background-color:black;
	color:white;
`

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

export default App;

props를 이용한 css 수정

import styled from "styled-components";

const Box = styled.div`
  width: 200px;
  height: 200px;
  background-color: ${(props) => props.bgColor};
`;

function App() {
  return (
    <div>
      <Box bgColor="teal" />
      <Box bgColor="tomato" />
    </div>
  );
}

export default App;

컴포넌트 확장

  • styled(<styled로 만든 컴포넌트>)< 추가할 css >
  • 똑같은 코드로 비슷한 컴포넌트를 생성하면 생산성이 떨어진다.
  • styled(컴포넌트)
    • ( )안에 들어간 스타일 컴포넌트의 속성을 모두 가져오고 백틱 안에 추가할 내용을 입력한다.
import styled from "styled-components";

const Box = styled.div`
  width: 200px;
  height: 200px;
  background-color: ${(props) => props.bgColor};
`;

// Box styled component의 속성들이 Circle에 복사된다.
const Circle = styled(Box)`
  border-radius: 50%;
`;

function App() {
  return (
    <div className="App">
      <Box bgColor="teal" />
      <Circle bgColor="tomato" />
    </div>
  );
}

export default App;

as, attrs

as
- as 키워드를 사용하면 컴포넌트의 스타일을 유지한채 원하는 태그로 바꿔줄 수 있다.

const Box = styled.div`
  display: block;
  width: 200px;
  height: 200px;
  background-color: ${(props) => props.bgColor};
`;
...
<Box as="a" href="/" bgColor="teal" /> // a 태그로 변한다. 
...

attrs
- attrs prop을 사용하면 원하는 옵션 값을 넣어 컴포넌트를 만들 수 있다.

const Input = styled.input.attrs({ required: true })`
  width: 400px;
  height: 60px;
  background-color: orange;
`;
...
<Input /> // required 옵션을 가진 input 태그가 되었다.
...

Animations

  • keyframes를 사용해 애니메이션 변수를 만들고 그것을 사용할 컴포넌트의 animation에 사용한다.
import styled, { keyframes } from "styled-components";

const rotateAnimation = keyframes`
  from{
    transform: rotate(0deg);
  }to{
    transform: rotate(360deg);
  }
`;

const Box = styled.div`
  display: block;
  width: 200px;
  height: 200px;
  background-color: ${(props) => props.bgColor};
  animation: ${rotateAnimation} 1s linear infinite;
`;

Selectors(선택자)

  • 아래와 같은 방법으로 컴포넌트 안에 있는 태그들에 대해 바로 style을 적용할 수 있다.
  • Box 컴포넌트 안에 span에 대한 css 코드.
const Box = styled.div`
  display: block;
  width: 200px;
  height: 200px;
  background-color: ${(props) => props.bgColor};
  animation: ${rotateAnimation} 1s linear infinite;
	span{
		font-size:25px;
		&:hover{
			font-size:40px;
		}
	}
`;
  • styled component 안에 styled componenet에 대한 선택자
const Imoji = styled.span`
  font-size: 25px;
`;
const Box = styled.div`
  display: block;
  width: 200px;
  height: 200px;
  background-color: ${(props) => props.bgColor};
  display: flex;
  justify-content: center;
  align-items: center;
  animation: ${rotateAnimation} 1s linear infinite;
  ${Imoji} {
    &:hover {
      font-size: 80px;
    }
  }
`;



Theme

  • dark mode / light mode를 구현하기 위해서는 최상위 루트에 ThemeProvider를 사용해야한다.
  • ThemeProvider에는 theme이라는 prop이 필요하다. ThemeProvider의 하위 컴포넌트들은 이 값을 참조할 수 있다.
import React from "react";
import ReactDOM from "react-dom/client";
**import { ThemeProvider } from "styled-components";**
import App from "./App";
import reportWebVitals from "./reportWebVitals";

**const darkTheme = {
  textColor: "whitesmoke",
  bgColor: "#111",
};

const lightTheme = {
  textColor: "#111",
  bgColor: "whitesmoke",
};**

const root = ReactDOM.createRoot(document.getElementById("root"));
root.render(
  <React.StrictMode>
    **<ThemeProvider theme={darkTheme}> // ThemeProvider로 app을 감싸준다.**
      <App />
    **</ThemeProvider>**
  </React.StrictMode>
);

Theme을 위한 index.d.ts 확장

  • 테마를 사용하기 위해 우리가 다운로드 했던 index.d.ts를 확장한다.
  • styled.d.ts 파일을 생성하고 테마에 사용할 타입을 정의한다.
// styled.d.ts
import "styled-components";

declare module "styled-components" {
  export interface DefaultTheme {
    textColor: string;
    bgColor: string;
  }
}

  • DefaultTheme interface를 가져와 테마에 적용
// theme.ts
import { DefaultTheme } from "styled-components";

export const lightTheme: DefaultTheme = {
  bgColor: "white",
  textColor: "tomato",
};

export const darkTheme: DefaultTheme = {
  bgColor: "black",
  textColor: "white",
};

  • ThemeProvider의 theme prop에 원하는 모드를 적용
// index.tsx
root.render(
  <React.StrictMode>
    <ThemeProvider theme={lightTheme}>
      <App />
    </ThemeProvider>
  </React.StrictMode>
);

  • styled components에서 사용
const Wrapper = styled.div`
  width: 100vw;
  height: 100vh;
  background-color: ${(props) => props.theme.bgColor || "#1f2937"};
  color: ${(props) => props.theme.textColor || "#1f2937"};
`;



Styled-reset

  • 스타일을 리셋하는 소스파일
npm i styled-reset

// App.tsx

import {Reset} from 'styled-reset'

const App = () =>{
	...
	<Reset/>
	... 
}
profile
나는야 프린이

0개의 댓글