# Mapping Components  in React

## Fetching JSON-like API Data

Very commonly you'll find yourself with an **array of data** that you want to display on the page. Using the vanilla JavaScript array method `.map()`, we can easily create a new array of components to display.&#x20;

This way, we can **avoid having to type out our data directly into the components**, and allow the data to live separately from the display of the data.

{% tabs %}
{% tab title="jokesData.js" %}

```javascript
// json-like API data
const jokesData = [
    {
        id: 1,
        punchLine: "It’s hard to explain puns to kleptomaniacs because they always take things literally."
    },
    {
        id: 2,
        question: "What's the best thing about Switzerland?",
        punchLine: "I don't know, but the flag is a big plus!"
    },
    {
        id: 3,
        question: "Did you hear about the mathematician who's afraid of negative numbers?",
        punchLine: "He'll stop at nothing to avoid them!"
    },
    {
        id: 4,
        question: "Hear about the new restaurant called Karma?",
        punchLine: "There’s no menu: You get what you deserve."
    },
    {
        id: 5,
        question: "Did you hear about the actor who fell through the floorboards?",
        punchLine: "He was just going through a stage."
    },
    {
        id: 6,
        punchLine: "He just needed a little space."
    }
]

export default jokesData
```

{% endtab %}

{% tab title="App.js" %}

```jsx
import React from "react"

import Joke from "./Joke"
import jokesData from "./jokesData"

function App() {

    // Mapping Json-like API Data
    const jokesComponents = jokesData.map((joke) => {
        return(
            <Joke 
                key = {joke.id}
                question = {joke.question}
                punchLine = {joke.punchLine} 
            />
        )
    })
    
    return (
        <div>
            {jokesComponents}
        </div>
    )
}

export default App
```

{% endtab %}

{% tab title="Joke.js" %}

```jsx
import React from "react"

function Joke(props) {
    return (
        <div>
            <h3 style={{display: !props.question && "none"}}>Question: {props.question}</h3>
            <h3 style={{color: !props.question && "#888888"}}>Answer: {props.punchLine}</h3>
            <hr/>
        </div>
    )
}

export default Joke
```

{% endtab %}

{% tab title="index.js" %}

```jsx
import React from "react"
import ReactDOM from "react-dom"

import App from "./App"

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

```

{% endtab %}

{% tab title="index.html" %}

```markup
<html>
    <head>
        <link rel="stylesheet" href="style.css">
    </head>
    <body>
        <div id="root"></div>
        <script src="index.pack.js"></script>
    </body>
</html>
```

{% endtab %}
{% endtabs %}
