| 일 | 월 | 화 | 수 | 목 | 금 | 토 |
|---|---|---|---|---|---|---|
| 1 | 2 | 3 | 4 | 5 | 6 | 7 |
| 8 | 9 | 10 | 11 | 12 | 13 | 14 |
| 15 | 16 | 17 | 18 | 19 | 20 | 21 |
| 22 | 23 | 24 | 25 | 26 | 27 | 28 |
Tags
- 메가바이트스쿨
- 모던 딥 다이브 자바스크립트
- 리액트
- 모던 자바스크립트 딥 다이브
- 프로그래머스
- react
- JavaScript
- 공식문서
- 개발 공부
- 비전공자
- Github
- useRef
- next.js
- 이벤트
- 알고리즘
- 패스트캠퍼스
- TypeScript
- 입문
- 내일배움카드
- 개발자취업부트캠프
- 국비지원교육
- 자바스크립트
- 프론트엔드
- useMemo
- 코딩테스트
- GIT
- styled-components
- CSS
- MegabyteSchool
- 자료구조
Archives
- Today
- Total
개발 기록 남기기✍️
Styled-Components (3) - "As" and Attrs 본문
Checkpoint 1
만약 컴포넌트의 태그는 input에서 a태그로 바꾸고 싶은데 스타일은 input 컴포넌트의 속성을 그대로 유지하고 싶을 때 어떻게 하면 좋을까?
"As"
import styled from "styled-components";
const Father = styled.div`
display: flex;
`;
const Btn = styled.button`
color: white;
background-color: tomato;
border: 0;
border-radius: 5px;
`;
function App() {
return (
<Father as="header">
<Btn>Log in</Btn>
<Btn as="a" href="/">
Log in
</Btn>
</Father>
);
}
export default App;

<Btn as="a" href="/" />처럼 컴포넌트 안에 as="tagname"을 입력해주면 Btn의 스타일은 유지하면서 태그를 원하는 태그로 바꿔줄 수 있다.
Checkpoint 2
컴포넌트를 이용해서 여러 개의 input을 삽입할 때, 모든 input에 required:true 속성을 주려고 한다.
import styled from "styled-components";
const Father = styled.div`
padding: 30px;
`;
const Input = styled.input`
display: block;
margin-bottom: 10px;
color: white;
background-color: tomato;
border: 0;
font-size: 30px;
border-radius: 5px;
`;
function App() {
return (
<Father as="header">
<Input required />
<Input required />
<Input required />
<Input required />
</Father>
);
}
export default App;

Input 컴포넌트를 넣을 때마다 일일이 required 속성을 작성해줘야하는 것일까?
Attrs
import styled from "styled-components";
const Father = styled.div`
padding: 30px;
`;
const Input = styled.input.attrs({ required: true, minlength: 10 })`
display: block;
margin-bottom: 10px;
color: white;
background-color: teal;
border: 0;
font-size: 30px;
border-radius: 5px;
`;
function App() {
return (
<Father as="header">
<Input />
<Input />
<Input />
<Input />
</Father>
);
}
export default App;

styled.input 뒤에 .attrs({required : true})를 입력했더니 잘 동작하는 것을 보았다. .attrs({required : true, minlength:10 })처럼 배열 형식으로 input태그에 공통적으로 들어갈 속성들을 지정해줄 수 있다.
'Front-End > React' 카테고리의 다른 글
| [React] 공식문서 정리 - 주요 개념(2) (0) | 2023.02.02 |
|---|---|
| [React] 공식문서 정리 - 주요 개념(1) (0) | 2023.02.01 |
| Styled-Component(4) - Animation and Pseudo Selectors (0) | 2022.12.09 |
| Styled-Components (2) - Adapting and Extending (0) | 2022.12.09 |
| Styled-Components (1) (0) | 2022.12.09 |