일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
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 |
- component
- Props
- route
- leetcode
- count
- Context
- event
- JSX
- state
- array
- DP
- axios
- React
- css
- treenode
- Navigation
- node.js
- MySQL
- bit
- routes
- BinaryTree
- server
- nodeJS
- c++
- queue
- priority_queue
- UE5
- Callback
- map
- 비트연산
- Today
- Total
우사미 코딩
[React] map 본문
animals 배열에 담겨있는 요소를
배열을 순회하면서 AnimalShow라는 컴포넌트를 만들고
컴포넌트의 type이라는 속성 값으로 배열의 각 요소를, key의 속성 값으로 현재 index를 props로 넘겨주고 싶은데여
그럼 map을 사용하면 됨!
* App.js
import AnimalShow from "./AnimapShow";
import { useState } from "react";
function getRandomAnimal(){
const animals = ['bird','cat','cow','dog','gator', 'horse'];
return animals[Math.floor(Math.random() * animals.length)];
}
function App(){
const[animals, setAnimals] = useState([]);
const handleClick = () =>{
setAnimals([...animals, getRandomAnimal()]);
}
const renderAnimals = animals.map((animal, index) => {
return <AnimalShow type = {animal} key={index}/>
});
return (
<div>
<button onClick={handleClick}>Add animal</button>
<div>{renderAnimals}</div>
</div>
);
}
export default App;
13행 : renderAnimals라는 함수를 정의
Array에 map이라는 함수를 사용하면 배열의 모든 요소를 꺼내서 읽거나 변경할 수 있다
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/map
Array.prototype.map() - JavaScript | MDN
The map() method creates a new array populated with the results of calling a provided function on every element in the calling array.
developer.mozilla.org
대충 저렇다고 함
20행 : renderAnimals호출
add animal 5번 클릭했을 때 결과
* image map
import bird from './svg/bird.svg';
import cat from './svg/cat.svg';
import dog from './svg/dog.svg';
import horse from './svg/horse.svg';
import gator from './svg/gator.svg';
import cow from './svg/cow.svg';
const svgMap = {
bird,cat,dog,horse,gator
// bird: bird, 과 같은 뜻 (import할 때 변수로 선언했기 때문)
// cat: cat,
// cow: cow,
}
function AnimalShow({type}){
return <img alt="animal" src={svgMap[type]}/>;
}
export default AnimalShow;
8행의 svgMap을 보면 그냥 변수를 쭈루룩 나열했는데
bird: bird, cat: cat과 동일한 뜻임
map사용은 AnimalChow에서 함
'React' 카테고리의 다른 글
[React] Axios, API (0) | 2023.06.25 |
---|---|
[React] css파일 불러오고 적용하기 (0) | 2023.06.23 |
[React] state - 배열 초기화, 새로운 요소 추가하기 (0) | 2023.06.23 |
[React] state 사용하기 (0) | 2023.06.23 |
[React] 이벤트 처리하기 - 콜백함수 정의 (0) | 2023.06.23 |