Map JSON, Javascript Object data to React Component – Code

We can easily map the JSON / JS object data to React component using Map function. Here is the example code of implementing the map function. In this example we will generating menu cards as per the json data.

categories.js

const categories = [
    {
      id: 1,
      name: "Shops",
      imgURL:
        "shops.png"
    },
    {
        id: 2,
        name: "Services",
        imgURL:
          "services.png"
      },
      {
        id: 3,
        name: "Education",
        imgURL:
          "education.png"
      },
      {
        id: 4,
        name: "Health",
        imgURL:
          "health.png"
      },
      {
        id: 5,
        name: "Personal",
        imgURL:
          "personal-care.png"
      },
      {
        id: 6,
        name: "Travel",
        imgURL:
          "transportation.png"
      },
      {
        id: 7,
        name: "Food",
        imgURL:
          "food.png"
      },
      {
        id: 8,
        name: "Movies",
        imgURL:
          "movies.png"
      },
      
  ];
  
  export default categories;
  

MenuCard.jsx

import React from "react";
import Card from 'react-bootstrap/Card';
import categories from '../data/categories';

function createCard(item){
    return(
       <Card  style={{ width: '4rem' }}>
            <Card.Img variant="top" src={`../images/card-icons/${item.imgURL}`} />
            <Card.Body>
            <Card.Title>{item.name} </Card.Title>
            </Card.Body>
       </Card>
     );
}

function MenuCard(){

    return(
        <div className="card-deck text-center"> 
          
                        {categories.map(createCard)} 
       
        </div>
    );
}

export default MenuCard;

App.js

import MenuCard from './components/MenuCard';

function App() {
  return (
    <div className="App">
      <Header/>    

     <div className="row  bg-light p-3">
      <div className="col-12">        
          <MenuCard />
        </div>
     </div>
    );
}

Output :

About the Author: smartcoder

You might like

Leave a Reply

Your email address will not be published. Required fields are marked *