Web/React

React - Styled Components 02

또롱또 2022. 5. 17. 20:06
728x90

1. ThemeProvider 

사용할려면 import 먼저해야하고

import { ThemeProvider } from 'styled-components'

아래처럼 적용하고싶은 범위에 theme을 적용가능하다.

const theme = {
  dark: {
    primary: '#000',
    text: '#fff',
  },
  light: {
    primary: '#fff',
    text: '#000',
  }

function App() {
  return (
    <ThemeProvider theme={theme}>
    
      <div className="App">
        <StyledButton>HELLO</StyledButton>
        <StyledButton danger>HELLO</StyledButton>
        <FancyButton>HELLO</FancyButton>
        <FancyButton as="a" href="https://google.com">GO TO GOOGLE</FancyButton>
        <SubmitButton>SUBMIT</SubmitButton>
        <LightButton>LIGHT</LightButton>
      </div>
      
    </ThemeProvider>
  );
}

다크모드를 만드는걸 예로들면 코드는 아래와 같이 props에 접근해서 theme객체안의 light객체안의 값에 접근가능

(위에서 2중객체로 만들었다.)

export const LightButton = styled(StyledButton)`
  border: 2px solid ${(props) => props.theme.light.primary};
  background-color: ${(props) => props.theme.light.primary};
  color:${(props) => props.theme.light.text};
`;

 

 

2. styled component로 새로 만든 컴포넌트 안의 속성을 사용하고 싶을때

inline 말고 이렇게 뒤에 .attrs({ //코드작성 }) 으로 가능하다.

export const SubmitButton = styled(StyledButton).attrs({
  type: 'submit' 
})`
  background-color: ${props => props.extended || "#EAB543"};
`;

 

3. 태그에 붙어있는 hover 같은 가상클래스 이용할때는

&:hover 이런식으로 만든다.

export const StyledButton = styled.button`
  background-color: ${props => props.danger? "#e74c3c" : "#2ecc71"};
  &:hover{
    background-color: green;
  }
`;

 

4. :root 같은 기본세팅도 공용css에서 되는가?

const GlobalStyle = createGlobalStyle`
:root {
        --adaptiveGray900: #ffffff;
    }
`;

똑같이 이용가능하다.

const S = {
  Wrapper: styled.div`
    background: var(--adaptiveGray50);
    color: var(--adaptiveGray900);
    height: 80vh;

    .color {
      color: var(--red);
    }
  `,
};

 

728x90

'Web > React' 카테고리의 다른 글

React - Route 5 --> 6  (1) 2022.05.20
React - 스파르타강의 2주차 숙제  (0) 2022.05.20
React - Styled Components 01  (0) 2022.05.16
React Hook 03 - useRef()  (1) 2022.05.16
React Hook 02 - useEffect()  (0) 2022.05.15