[Styled-components] 기본 개념 정리

이영우·2023년 4월 28일
0

마크업 / 스타일링

목록 보기
1/1
post-thumbnail

✅ 원래 HTML / 리액트에서 CSS를 적용하던 방식은, HTML 선택자를 만들고, className이나 style을 부여하는 작업이 필요했다. 하지만 Styled Component를 사용하면 스타일도 컴포넌트로 관리 할 수 있다.

✅ 스타일링 된 컴포넌트를 사용하며, 컴포넌트 함수 내에 스타일을 쓸 필요가 없어 가독성이 훨씬 좋고 더불어 알아보기 쉬운 이름을 지을 수 있다.

//선언 방식
const Wrapper = styled.div`
  display: flex;
  height: 90vh;
  flex-direction: row;
  justify-content: center;
  align-items: center;
`;

Style 컴포넌트에 Props 보내기

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

---

function App() {
  return (
    <Wrapper>
    <Box bgColor="teal" />
    <Box bgColor="navy" />
    </Wrapper>
  );
}
  • 똑같은 컴포넌트를 생성하지 않고, Props를 인자로 받아 Box 컴포넌트에 전달해줄 함수를 만들어 중복된 코드를 만들지 않고, 설정 가능한 Box 컴포넌트를 만들 수 있다.

컴포넌트 extend

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

const Circle = styled(Box)`
  border-radius: 50px;
`;
  • Box의 속성은 그대로 가져오되, 내가 추가하고 싶은 속성을 백틱 안에 적어준다.

Html 태그만 바꾸고 싶을 때

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

---

<Btn>Log in</Btn>
<Btn as="a" href="/">Log in</Btn>
  • 만약, 스타일링은 그대로 가져오고 Html 태그만 변경하고 싶을 땐, as=”태그이름” 을 사용하여 태그를 변경 할 수 있다.

컴포넌트가 반복되는데, 모든 컴포넌트에 Html 속성을 지정할 때

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

--- 

<Input />
<Input />
<Input />
  • 컴포넌트가 반복되는데, 모두 다 같은 속성을 가져야 할 때 styled.태그이름 뒤에 attrs를 추가하여 모든 Input에 적용한다. 이를 통해 attribute를 한번만 써줘도 될 뿐더러, 코드도 깔끔해진다.
  • attrs 괄호 안에 들어가는 것들은 object 형태여야 한다.

애니메이션

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

//keyframes helper (애니메이션 코드)
const animation = keyframes`
  0% {
    transform: rotate(0deg);
    border-radius: 0px;
  }
  50% {
    border-radius: 100px;
  }
  100% {
    transform: rotate(360deg);
    border-radius: 0px;
  }
`;

---

//애니메이션을 받을 컴포넌트
const Box = styled.div`
  width: 200px;
  height: 200px;
  background-color: violet;
  animation: ${animation} 3s linear infinite;
`;
  • keyframes를 import하여 편리하게 애니메이션을 생성 할 수 있다.
  • animation 컴포넌트를 Box 안에서 ${animation} 형태로 불러와서, 적용시킬 수 있다.

로딩 UI를 따라만들며 작성했던 코드


Pseudo Selector

const Emoji = styled.span`
  font-size: 20px;
`;

const Box = styled.div`
  width: 200px;
  height: 200px;
  ${Emoji} {
    &:hover {
      font-size: 30px;
    }
  }
`;

---

<Wrapper>
  <Box>
	  <Emoji>🔮</Emoji>
  </Box>
</Wrapper>
  • Styled Component “안에” 있는 것들을 select 할 수 있도록 도와주는 선택자이다.
  • ${Emoji} 형태로 컴포넌트를 불러와, Box 안에 있는 Emoji 컴포넌트를 선택하여 속성을 줄 수 있다.
  • & 선택자로 Emoji(자기 자신) 컴포넌트를 지칭할 수 있다.


styled-components의 기본 개념에 대한 글입니다. 최신 버전에서 해당 내용이 변경되었을 수 있습니다. 부족하거나 맞지 않는 부분이 있다면, 댓글로 알려주세요!
styled-components: Basics 공식 문서 링크

profile
학습한 기술 지식들을 기록합니다.

0개의 댓글