map과 전개연산자

뭐라구요·2023년 6월 15일
0

🔄 map() 이란?

map() 은 반복되는 컴포넌트를 랜더링 하기 위해 Js 배열의 내장 함수인 map() 을 사용한다. 또 map() 은 매개변수로 전달된 함수를 사용하여 배열 내 각 요소를 원하는 규칙에 다라 변환한 후 새로운 배여을 생성한다. 그럼 간단한 예시코드를 보며 알아보자.

let list = [1,2,3]
list.map(()=>{
  console.log("Mikel Arteta");
});


이와 같이 아르테타가 3번 나온 걸 확인 할 수 있다. 이제 map 에 매개변수로 들어가는 함수의 매개변수를 이용해보자.

let list = ['Saka', 'Ødegaard', 'Xhaka']
list.map((e)=>{
  console.log(e);
});


다음 코드에서 map 의 파라미타 함수에 매개변수 e 를 주고, 그 e를 이용하여 list 에 있는 요소들을 순서대로 쓸 수 있는 것을 알 수 있다.

👷‍ map() 활용하기

앞에서 정리한 map() 을 컴포넌트를 이용해 활용하면 여러개의 데이터를 하드코딩 하지 않고 반복문을 사용해 간결히 끝낼 수 있다.
Data.js

export default [
    {
        setup: "I got my daughter a fridge for her birthday.",
        punchline: "I can't wait to see her face light up when she opens it."
    },
    {
        setup: "How did the hacker escape the police?",
        punchline: "He just ransomware!"
    },
    {
        setup: "Why don't pirates travel on mountain roads?",
        punchline: "Scurvy."
    },
    {
        setup: "Why do bees stay in the hive in the winter?",
        punchline: "Swarm."
    },
    {
        setup: "What's the best thing about Switzerland?",
        punchline: "I don't know, but the flag is a big plus!"
    }
]

다음 데이터를 이용하여<Joke /> 라는 컴포넌트를 만들어보자.
App.jsx

import Joke from "./components/Joke";
import JokesData from "./components/JokesData";export default function App() {
  const JokeElements = JokesData.map((joke) => {
    return <Joke setup={joke.setup} punchline={joke.punchline} />;
  });return <div className="App">{JokeElements}</div>;
}

Joke.jsx

export default function Joke(props) {
  return (
    <div>
      {props.setup && <h3>{props.setup}</h3>}
      {props.punchline && <p>{props.punchline}</p>}
      <hr></hr>
    </div>
  );
}

다음 코드에서는 .map() 을 사용하여 JokesData 에 있는 setuppunchline 을 순서대로 넘겨주며 Joke 컴포넌트를 랜더링 하고 있는 것을 알 수 있다. Joke.js 에서 4, 5번 째 줄에 있는 코드의 의미는 받아온 setuppunchline 의 값이 있을 때만 뒤에 있는 태그를 랜더링 하겠다는 뜻을 의미한다.

🥅 전개연산자(...)

전개연산자는 코드를 축약하기 위한 기법 중 하나이다. 주로 배열을 이용할 때 사용되며, 그 기능은 객체 또는 배열을 펼친다는 것이다. 배열을 펼친다는 것이 이해가 잘 되지 않을 수 있다. 코드를 통해 더 자세히 알아보자.

let list = [];
let list1 = [1,2,3];
let list2 = [4,5,6];
ㅤ
list = [list1,list2];
console.log(list) // [[1,2,3], [4,5,6]]
ㅤ
list = [...list1,...list2];
console.log(list) // [1,2,3,4,5,6]

다음 코드에서 알 수 보았듯이 전개연산자를 사용하지 않으면 배열 그 자체가 list 에 들어가지만 전개연산자를 사용하면 배열 내의 있는 값들이 펼쳐져 list 에 들어가는 것을 알 수 있다.

👨‍🔧 전개연산자 활용하기

이번에는 앞서 이야기 했던 전개연산자를 props 와 함께 활용해 보자.

다음은 가상의 사이트를 구축한 것이다.
Data.js

export default [
  {
    id: 1,
    title: "Life Lessons with Katie Zaferes",
    description:
      'I will share with you',
    price: 136,
    stats: {
      rating: 5.0,
      reviewCount: 6
    },
    location: "Online",
    openSpots: 0
  },
  {
    id: 2,
    title: "Learn Wedding Photography",
    description:
      "Interested in becoming a wedding photographer?",
    price: 125,
    stats: {
      rating: 5.0,
      reviewCount: 30
    },
    location: "Online",
    openSpots: 27
  },
  {
    id: 3,
    title: "Group Mountain Biking",
    description:
      "Experience the beautiful",
    price: 50,
    stats: {
      rating: 4.8,
      reviewCount: 2
    },
    location: "Norway",
    openSpots: 3
  }
];

App.js

import Card from "./components/Card";
import data from "./components/Data";const CardData = data.map((item) => {
  return <Card {…item} />;
  // return <Card item = {item} />;
  // return <Card openslote = {item.openslote} …>
});export default function App() {
  return (
    <div className="App">
      <section className="cardsList"> {CardData} </section>
    </div>
  );
}

App.js 에서는 map() 내의 item 이라는 매개변수를 이용하여 데이터를 Card 컴포넌트에 넘겨주는 코드다. 이 때 넘겨주는 방식이 총 3가지가 있다.
먼저 첫 번째 return 문은 전개연산자를 이용해 item 객체를 분해하여 Card 에 전달하기 때문에 Card에서 props.rating 과 같이 접근이 가능하다.
두 번째 return 문은 item 의 값으로 가지는 객체를 Card 에 전달하기 때문에 props.item.rating 과 같이 접근해야한다는 이전 방식 보다 비교적 까다로운 방법으로 값에 접근을 할 수 있다.
마지막 return 문의 의미는 그 매개변수를 직접 하나 씩 정해줘야 하고, 그렇지 못하면 접근을 할 수 없는 어려움이 있다.

오늘은 map()전개연산자 에 대하여 알아보았다.

0개의 댓글