React
map() 함수
projaewoo
2021. 1. 21. 17:32
map함수 용도
- 반복되는 컴포넌트를 랜더링 가능
map함수 문법
arr.map(callback, [thisArg])
- callback
- 새로운 배열의 요소를 생성하는 함수
- 파라미터 종류
- currentValue
- 현재 처리하고 있는 요소
- index
- 현재 처리하고 있는 요소의 index값
- array
- 현재 처리하고 있는 원본 배열
- currentValue
- 파라미터 종류
- 새로운 배열의 요소를 생성하는 함수
- thisArg (선택 항목)
- callback 함수 내부에서 사용할 this 레퍼런스
예제
var numbers = [1, 2, 3, 4, 5];
const result = numbers.map(num => num * num);
console.log(result);
import React from 'react';
const IterationSample = () => {
const names = ['A', 'B', 'C', 'D'];
const nameList = names.map(name123 => <li>{name123}</li>);
return(
<ul>{nameList}</ul>
);
}
export default IterationSample;
- <li> ... </li> JSX코드로 된 배열을 새로 생성한 뒤, nameList에 저장
key
정의
- 컴포넌트 배열을 랜더링할 때, 어떤 원소에 변동이 있었는지 확인하는 용도
- 유일한 값으로 설정
예제
import React from 'react';
const IterationSample = () => {
const names = ['A', 'B', 'C', 'D'];
const nameList = names.map( (name123, index) => <li key = {index}>{name123}</li>);
return(
<ul>{nameList}</ul>
);
}
export default IterationSample;
- names배열을 출력하는 예제
import React, {useState} from 'react';
const IterationSample = () => {
const [names, setNames] = useState([
{id : 1, text : 'A'},
{id : 2, text : 'B'},
{id : 3, text : 'C'},
{id : 4, text : 'D'}
]);
const [inputText, setInputText] = useState('');
const [nextId, setNextId] = useState(5); //새로운 항목을 추가할 때 사용할 id
const onChange = (e) => {
setInputText(e.target.value)
};
const onKeyPress = (e) => {
if(e.key === 'Enter') {
onClick();
}
};
const onClick = () => {
const nextNames = names.concat({
id : nextId, //nextId값을 id로 설정하고
text : inputText //onChange에 의해 e.target.value는 inputText에 저장되어있음.
}); //names배열 뒤에 입력된 text를 붙이고. //nextNames배열 길이 : 5
setNextId(nextId + 1);
setNames(nextNames); //names배열을 업데이트 //names배열 길이 : 5
setInputText(''); //inputText를 비움.
};
const onRemove = id => { //id를 파라미터로 받음.
const nextNames = names.filter(namesElements => namesElements.id !== id);
//names배열에서 파라미터로 받은 id만 제외해서 nextNames에 저장.
setNames(nextNames); //파라미터로 받은 id를 제외한 nextNames배열을 names에 저장.
};
const nameList = names.map(name =>
<li key = {name.id} onDoubleClick = {() => onRemove(name.id)}> {/*name의 id를 파라미터로 넘겨줌*/ }
{name.text}
</li>
);
return(
<>
<input
value = {inputText}
onChange = {onChange}
onKeyPress = {onKeyPress}
/>
<button onClick = {onClick}>추가</button>
<ul>{nameList}</ul>
</>
);
}
export default IterationSample;
- 입력한 값을 배열로 받아 출력, 제거하는 예제
- filter 함수
- 배열에서 특정 조건을 만족하는 원소들만 쉽게 분류
- ex)
- const numbers = [1, 2, 3, 4, 5, 6];
const withoutThree = numbers.filter(number => number !== 3);
결과 : [1, 2, 4, 5, 6]
- const numbers = [1, 2, 3, 4, 5, 6];
- ex)
- 배열에서 특정 조건을 만족하는 원소들만 쉽게 분류
- onDoubleClick 이벤트
- HTML요소를 더블클릭할 때 사용하는 이벤트
- filter 함수