Notice
Recent Posts
Recent Comments
Link
일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
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 | 29 | 30 |
31 |
Tags
- 기지국 설치 자바스크립트
- 리덕스
- 우선순위 큐 자바스크립트
- 알고리즘 수업-깊이 우선 탐색1
- 13023번 ABCDE
- Java
- 24480번
- Redux
- 힙 자바스크립트
- 백준
- 1389번 케빈 베이컨의 6단계 법칙
- 1937번 욕심쟁이 판다
- 2275번
- 1303번
- level1
- ssh
- 기지국 설치 js
- JavaScript
- level0
- 백준 1068번 트리
- 알고리즘
- 백준 1068
- React
- dfs
- 프로그래머스
- 2638번 치즈
- 백준 13023번
- 자바스크립트
- 부녀회장이 될 테야
- 백준 2638번
Archives
- Today
- Total
코딩왕랄프👊🏻
[React] Component Mapping 본문
반응형
SMALL
안녕하세요!
오늘은 이전 자바스크립트의 map() 메소드에 이어, React의 컴포넌트를 Mapping하는 방법에 대해 배워보도록 하겠습니다.
아래 사진과 같이 이름과 전화번호로 나눠져 있는 데이터들을 나타내는 예제로 살펴보겠습니다.
1. 가장 기본적인 코드
class App extends React.Component {
render(){
return (
<Contacts/>
);
}
}
class Contacts extends React.Component {
render(){
return(
<div>
<h1>Contacts</h1>
<ul>
<li>Abet 010-0000-0001</li>
<li>Betty 010-0000-0002</li>
<li>Chalie 010-0000-0003</li>
<li>David 010-0000-0003</li>
</ul>
</div>
);
}
}
=> 정말 가장 기본적인 코드죠?
Contact 클래스 내에 일일이 데이터들을 <li> 태그로 적어주었고, 그것을 App 클래스에서 call 하였습니다.
그럼 좀 더 나은 방법을 사용해볼까요?
2.
class ContactInfo extends React.Component {
render() {
return(
<li>{this.props.name} {this.props.phone}</li>
);
}
}
class Contacts extends React.Component {
render(){
return(
<div>
<h1>Contacts</h1>
<ul>
<ContactInfo name="Abet" phone="010-0000-0001"/>
<ContactInfo name="Betty" phone="010-0000-0002"/>
<ContactInfo name="Charlie" phone="010-0000-0003"/>
<ContactInfo name="David" phone="010-0000-0004"/>
</ul>
</div>
);
}
}
=> Contacts 클래스에서 ConatactInfo 클래스를 사용하였는데요.
ContactInfo는 this.props를 사용했고 name과 phone으로 두 데이터를 분리시켰습니다.
3. 이제 데이터를 mapping 해볼 차례 입니다!
import React from 'react';
class App extends React.Component {
render(){
return (
<Contacts/>
);
}
}
class Contacts extends React.Component {
constructor(props) {
super(props);
this.state = {
contactData: [
{name: "Abet", phone: "010-0000-0001"},
{name: "Betty", phone: "010-0000-0002"},
{name: "Charlie", phone: "010-0000-0003"},
{name: "David", phone: "010-0000-0004"}
]
};
}
render(){
return(
<div>
<h1>Contacts</h1>
<ul>
{this.state.contactData.map((contact, i) => {
return (<ContactInfo name={contact.name}
phone={contact.phone}
key={i}/>);
})}
</ul>
</div>
);
}
}
class ContactInfo extends React.Component {
render() {
return(
<li>{this.props.name} {this.props.phone}</li>
);
}
}
export default App;
=> Contacts 클래스에서, constructor를 통해 contactData들을 정의하였고 , return 부분에서 이 데이터들을 mapping 했는데요!
이때, ContactInfo 클래스를 이용하여 mapping 한 것을 볼 수 있습니다!
여기서 사용된 key는 child 컴포넌트에 독자성 (identity)을 부여한 것이라고 합니다!
참고자료
반응형
LIST