1 분 소요

📖 지난 글 보기


안녕하세요. Nerd Lee 입니다.

지난 글에서, styled-components를 클래스처럼 상속받아서 확장시켜 사용하는 방법에 대해서 알아봤습니다.

이번 글에서는 styled-components에서 사용되는 as와 Attrs에 대해서 알아보도록 하겠습니다.


Styled-Components as | Attrs


1. as란 무엇일까?

이렇게 코드를 작성해보세요.

import styled from "styled-components";

const Parent = styled.div`
  display: flex;
`;

const Button = styled.button`
  background-color: black;
  color: white;
  border: 0;
  border-radius: 5px;
`;

function App() {
  return (
    <Parent>
      <Button>로그인</Button>
    </Parent>
  );
}

export default App;
  • 저는 button이란 태그를 가지고 있는 styled-components를 사용하려고 합니다.
    그런데, 만약 anchor 태그를 가지고 싶은데, Button에 있는 속성값은 그대로 사용하고 싶다면 어떻게 해야할까요?
    그 때 사용하는 게 as라는 것입니다.
import styled from "styled-components";

const Parent = styled.div`
  display: flex;
`;

const Button = styled.button`
  background-color: black;
  color: white;
  border: 0;
  border-radius: 5px;
`;

function App() {
  return (
    <Parent>
      <Button>로그인</Button>
      <Button as="a">전 a 태그입니다.</Button>
    </Parent>
  );
}

export default App;
  • 이러면, Button의 속성은 그대로 사용하고, a 태그로 사용이 되게 됩니다.
    버튼 태그에서는 사용하지 못하는 href 속성을 a 태그로 사용이 가능해지거든요.

2. Attrs란 무엇일까?

Parent만 빼고 모두 지운 다음, Input을 추가해봅시다.

import styled from "styled-components";

const Parent = styled.div`
  display: flex;
`;

const Input = styled.input`
  background-color: black;
`;

function App() {
  return (
    <Parent>
      <Input placeholder="hello" />
      <Input placeholder="hello" />
      <Input placeholder="hello" />
      <Input placeholder="hello" />
      <Input placeholder="hello" />
    </Parent>
  );
}

export default App;
  • 자 이렇게, 많은 Input이 있고, 모든 Input의 placeholder 속성값을 hello 라고 하고 싶다라고 에를 들어보겠습니다.
    그런데, 여기서 hello가 아니라 bye라고 하고 싶으면, 저 5개를 다 수정해야하는데
    프로그래머들은 저런 귀찮은 작업 하기 싫어하잖아요ㅠㅠ 그래서 styled-components에서 제공하는 것이 attrs 함수 입니다!

이렇게 한 번 코드를 수정해보세요.

import styled from "styled-components";

const Parent = styled.div`
  display: flex;
`;

const Input = styled.input.attrs()`
  background-color: black;
`;

function App() {
  return (
    <Parent>
      <Input />
      <Input />
      <Input />
      <Input />
      <Input />
    </Parent>
  );
}

export default App;
  • styled.input.attrs() 를 해줍니다. 그러면 attrs 함수를 사용할 수 있는데요.
    attrs 함수로, input 태그에 있는 속성값을 가질 수 있습니다. 그래서, 만약 같은 태그에 같은 속성을 사용한다면
    attrs에 속성값만 추가해주면 된다는 것입니다!

이렇게 말이죠!!

const Input = styled.input.attrs({ placeholder: "hello" })`
  background-color: black;
`;
  • 이렇게 하면, bye로 바꾸고 싶으면, hello를 bye로만 바꿔주면 됩니다ㅎㅎㅎ 참 쉽죠?


이 글이 도움이 되셨다면 댓글 부탁드립니다^^
다음 글로 찾아오겠습니다!