styled-components

yezee·2023년 4월 19일
0

라이브러리

목록 보기
2/8
post-thumbnail

설치

npm i styled-components

스타일 상속 및 확장

import styled from 'styled-components';

const Father = styled.div`
  display: flex;
`;
const Box = styled.div`
  background-color: ${(props) => props.bgColor}; //adapting style
  width: 100px;
  height: 100px;
`;
const Circle = styled(Box)` //extending style
  border-radius: 50px;
`;

function App() {
  return (
    <Father>
      <Box bgColor='teal' />
      <Circle bgColor='tomato' />
    </Father>
  );
}

export default App;

as and attrs()

as을 사용하여 엘리먼트를 다른 엘리먼트로 교체

const Btn = styled.button`
  color: white;
  background-color: tomato;
  border: 0;
  border-radius: 15px;
`;

function App() {
  return (
    <Father>
      <Btn>Log in</Btn> //버튼태그
      <Btn as='a'>Log in</Btn> //as사용으로 버튼태그에서 a태그로 변경
    </Father>
  );
}

export default App;

attrs()를 통해 태그 속성값을 전체 지정할 수 있다

const Input = styled.input.attrs({ required: true, minLength: 10 })`
  background-color: tomato;
`;

에니메이션

import styled, { keyframes } from 'styled-components';

const rotation = keyframes`
from{
  transform:rotate(0deg)
}
to{
  transform: rotate(360deg);
}
`;
const Box = styled.div`
  height: 200px;
  width: 200px;
  background-color: tomato;
  animation: ${rotation} 1s linear infinite;
`;

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

export default App;

Themes

다크모드와 같은 기능을 구현할 때 유용하게 사용할 수 있다
전체에 다크모드와 같은 기능을 적용하기 위해 index.js파일에서 작업이 필요하다

상반된 효과를 줄 변수 두가지를 만들어준다
ex) darkTheme과 lightTheme
이때, 속성값은 같게 만들어주어야한다-> textColor, backgroundColor

//index.js
import { ThemeProvider } from 'styled-components';

const darkTheme = {
  textColor: 'whitesmoke',
  backgroundColor: '#111',
};

const lightTheme = {
  textColor: '#111',
  backgroundColor: 'whitesmoke',
};

const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(
  <React.StrictMode>
    <ThemeProvider theme={darkTheme}> //theme에서 darkThem과 lightThem만 변경해주면 다크모드를 구현할 수 있다
      <App />
    </ThemeProvider>
  </React.StrictMode>
);

app.js에서 prop로 theme값을 전달해준다

//app.js
const Wrapper = styled.div`
  display: flex;
  height: 100vh;
  width: 100vw;
  justify-content: center;
  align-items: center;
  background-color: ${(props) => props.theme.backgroundColor};
`;

const Title = styled.h1`
  color: ${(props) => props.theme.textColor};
`;

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

export default App;

createGlobalStyle

전역 스코프에 스타일을 올려주는 것

import {createGlobalStyle} from "styled-components"

const GlobalStyle=createGlobalStyle`
body{
color:red;
}
`
profile
아 그거 뭐였지?

0개의 댓글