React renders arrays, Mapping components

Juyeon Lee·2022년 4월 26일
0

REACT 리액트

목록 보기
13/65

React에서 arrays을 render하는 코드를 살펴보자

App.js

import React from "react"


export default function App() {
    const colors = [
            <h3>Red</h3>, 
            <h3>Orange</h3>, 
            <h3>Yellow</h3>,
            <h3>Green</h3>,
            <h3>Blue</h3>,
            <h3>Indigo</h3>,
            <h3>Violet</h3>
        ]
    return (
        <div>
            {colors}
        </div>
    )
}
      

이렇게하면 저기 array에 있는애들이 {color}로 다 rendering 됨...
components을 mapping하는걸 밑의 코드를 보고 이해해보자.

jokesData.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!"
    }
]

이렇게 array으로 된 파일을 만들어주고

Joke.js

import React from "react"

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

Joke.js에서는 저번에 했던 것처럼 render해줄애들 적어준 상태고

여기서 중요한건 바로

App.js

import React from "react"
import Joke from "./Joke"
import jokesData from "./jokesData"

export default function App() {
    const jokeElements = jokesData.map(joke => {
        return <Joke setup={joke.setup} punchline={joke.punchline} />
    })
    return (
        <div>
            {jokeElements}
        </div>
    )
}

여기서 map을 이용해서 return 해줌...
뜨하하하하...점점 조금 어려워지기 시작하는군??ㅋㅋㅋ

참고로 index.js는 그대로

import React from "react"
import ReactDOM from "react-dom"
import App from "./App"


ReactDOM.render(<App />, document.getElementById("root"))

0개의 댓글