Front-End/React(비공)

[React] styled components 1

리리히히 2024. 3. 19. 16:19
반응형

 

※ 해당 글은 노마드코더의 강의를 듣고 복습 및 기록을 위한 포스팅입니다.

 

import styled from "styled-components"

const Father = styled.div`
  /* display: flex; */
`;

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

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

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


function App() {
  return (
    <Father>
      <Box bgColor="yellow" />
      <Circle bgColor="tomato" />
      <Input />
      <Input />
      <Input />
      <Input />
      <Input />
      <Input />
    </Father>
  );
}

export default App;

 


 

🔎 코드 쪼개서 설명

import styled from "styled-components"
  • styled-components를 사용하기 위해서는 파일 제일 상단에 import 해주어야한다.

 

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

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

const Input =styled.input.attrs({required: true, minLength:10})`
  background-color: tomato;
  • 해당 부분들은 스타일컴포넌트 (styled-components)
  • 배경색이 다른 값은
     background-color: ${(props) => props.bgColor};
    bgColor라는 props를 통해 받아온다.
  • attrs는 속성값을 추가 할 수 있다.
    styled.input.attrs({required: true, minLength:10})

 

 

 

function App() {
  return (
    <Father>
      <Box bgColor="yellow" />
      <Circle bgColor="tomato" />
      <Input />
      <Input />
      <Input />
      <Input />
      <Input />
      <Input />
    </Father>
  );
}

export default App;
  • 컴포넌트를 설정하면 설정한 컴포넌트만 가져다가 스타일을 적용시킬 수 있다.
반응형