Search code examples
reactjsarrow-functions

React/JSX Arrow function for JSON object with array.


I have the following JSON object

const slides = [
  {
    title: "Hello World",
    bullets: [
      "Allows us to ... write",
      "Allows us to ... writez",
      "Allows us to ... writezz",
    ],
    slideIndex: 0,
  },
  {
    title: "Hello Worldz",
    bullets: [
      "Allows us to ... write",
      "Allows us to ... writez",
      "Allows us to ... writezz",
    ],
    slideIndex: 1,
  },
];

Now I want to use the following component Slide.js

import React from "react";

const Slide = slide => (
  <div>
    <h1> { slide.title } </h1>
    <ul>
      { slide.bullets.map( bullet => <li> { bullet } </li>)}
    </ul>
  </div>
);

export default Slide;

Inside my App.js to display the content of the slides variable.

import React, { Component } from 'react';
import './App.css';
import Slide from "./components/Slide.js";

const slides = [ ... ];

class App extends Component {
  render() {
    return (
      <div className="App">
        <Slide slide={slides} />
      </div>
    );
  }
}

export default App;

How can I loop over the bullets array? I already tried slide.bullets[bullet].map(...) but that didn't work.


Solution

  • const slides = [
      {
        title: "Hello World",
        bullets: [
          "Allows us to ... write",
          "Allows us to ... writez",
          "Allows us to ... writezz"
        ],
        slideIndex: 0
      },
      {
        title: "Hello Worldz",
        bullets: [
          "Allows us to ... write",
          "Allows us to ... writez",
          "Allows us to ... writezz"
        ],
        slideIndex: 1
      }
    ];
    
    const Slide = props => {
      return (
        <div>
          <h1>{props.slide.title}</h1>
          <ul>{props.slide.bullets.map(bullet => <li> {bullet} </li>)}</ul>
        </div>
      );
    };
    
    class App extends React.Component {
      render() {
        return (
          <div className="App">{slides.map(slide => <Slide slide={slide} />)}</div>
        );
      }
    }
    
    ReactDOM.render(<App />, document.getElementById("app"));
    <script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>
    <div id="app"></div>