우사미 코딩

[React] map 본문

React

[React] map

맑은 눈의 우사미 2023. 6. 23. 14:47
반응형

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에서 함

반응형
Comments