리액트는 맵핑 시 자바스크립트 문법을 그대로 사용할 수 있다.
map() 메소드는 파라미터로 전달 된 함수를 배열의 각 요소에 처리 후, 결과를 새로운 배열로 return 한다.
Arr.map(callback, [thisArg])
1. callback: 새로운 배열의 요소를 생성, 세 가지 인자를 가짐
1. currentValue: 현재 처리되고 있는 요소
2. index: 현재 요소의 index
3. array: 메소드가 호출된 배열
2. thisArg(선택): callback 함수 내부에서 사용할 this의 값 지정
render(){} 블럭 내에 작성
사용 시 return에서 {함수()} 형태로 작성
import './App.css';
import React from 'react'
class ContactInfo extends React.Component{
render(){
return(
<div>
{this.props.contact.name}
{this.props.contact.phone}
</div>
)
}
}
class Contact extends React.Component{
constructor(props){
super(props);
this.state={
contactData: [
{name: 'a', phone: '010'},
{name: 'b', phone: '011'},
{name: 'c', phone: '016'},
{name: 'd', phone: '018'},
]
}
}
render(){
const mapToComponent = (data) =>{
return (data.map((contact, i) => {
return (<ContactInfo contact={contact} ket={i} />)
}))
}
return(
<>
{mapToComponent(this.state.contactData)}
</>
)
}
}
function App() {
return (
<Contact />
);
}
export default App;