개발/자바스크립트

[리액트] - styled component

대왕판다 2022. 1. 9. 21:15

1. props 활용

  - 동일한 컴포넌트에 특정 prop에 다른값을 주고싶을때

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

//inside of rendered component	
	<Box bgColor="teal" />
    	<Box bgColor="tomato" />

 

2. extend 활용

 - 이미 만들어진 컴포넌트를 확장하여 사용

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

const Circle = styled(Box)`
  border-radius: 50px;
`;

 

3. as

 - 컴포넌트 내 prop은 같되 html 태그를 변경

const Btn = styled.button`
  color: tomato;
`;

// inside of rendered function

      <Btn>Log in</Btn>
      <Btn as="a">Go Home</Btn>

4. attributes

  - input 태그의 required, maxLength 등 활용가능

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

 

5. animations

 import keyframes 필요 애니메이션의 변수명은 당연하게도 소문자 시작 

const animation = keyframes`
  0% {
  }
  100%{
  }
  `;
  
  const Box = styled.div`
    animation: ${animation} 1s linear infinite;
  `;

 

6. pseudo Selector, state selector

  - 일반적인 css 수도 셀렉터와 비슷하게 특정 부모 하위 요소 스타일링 가능. but 문법은 다름

   

const Box = styled.div`  
  height: 200px;
  width: 200px;
  span {
    font-size: 36px;
    &:hover {
      font-size: 40px;
    }
    &:active {
      opacity: 0;
    }
  }
 // span:active 로도 사용 가능 
`;

 

and 컴포넌트 속 컴포넌트도 타겟으로 가능

const Title = styled.h1`
  color: tomato;
  &:hover {
    color: teal;
  }
`;

const Wrapper = styled.div`
  display: flex;
  height: 100vh;
  width: 100vw;
  justify-content: center;
  align-items: center;
  ${Title}:hover {
    font-size: 99px;
  }
`;

 

7. themes

 themeProvider 속 theme 을 결정하고 <ThemeProvider>로 감싸진 component 안에서는

ReactDOM.render(
  <React.StrictMode>
    <ThemeProvider theme={darkTheme}>
      <App />
    </ThemeProvider>
  </React.StrictMode>,
  document.getElementById("root")
);

prop를 활용해

background-color: ${(props) => props.theme.backgroundColor};

이런식으로 가져올 수가 있음. 물론 각각의 theme 내 prop 이름은 같아야한다.

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

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

요런식으로

 

 

-

정리를 해뒀지만, 어차피 연습을 질리게 할 예정