Home > front end >  Trying to parse a local json string to call a function
Trying to parse a local json string to call a function

Time:04-30

I am receiving a local JSON to simulate an API connection, in the project I have some images working with imports: import product_1 from '../../assets/image/product_1.png'; but in my local JSON I have an image key with the products, my problem is trying to call that key.

This is my local JSON:

{
    "products": 
    [
        {
            "id": 1,
            "name": "CAMISA DE DOTACIÓN PARA PERSONAL DE VIGILANCIA Y SEGURIDAD PRIVADA",
            "image": "Product_1"
        },
        {
            "id": 2,
            "name": "CAMISA O BLUSA DE DOTACIÓN PARA PERSONAL ADMINISTRATIVO Y/O DE PLANTA INDUSTRIAL",
            "image": "Product_2"
        },
        {
            "id": 3,
            "name": "CAMISA EN JEAN",
            "image": "Product_3"
        },
        {
            "id": 4,
            "name": "Product 4",
            "image": "Product_4"
        },
        {
            "id": 5,
            "name": "Product 5",
            "image": "Product_5"
        }
    ]
}

and this is my map in react:

import React, { useState } from 'react';
import { 
  product_1,
  product_2,
  product_3
} from '../components/utils/Images';
import data from '../assets/data/products.json'

const Catalogo = () => {
  return(
    {
      data.products.map((product, index) => {
        return (
         <div className='col-3'>
           <Image src={product.image}/> 
           // this line will return <Image src={product_1}/>
             <Button variant="primary" style={{zIndex:"40"}} onClick={() => counter(index)}>Ver</Button>
         </div>
        )
      })
    }
  )
}

export Catalogo

CodePudding user response:

Have you try with ...{ "id": 1, "name": "CAMISA DE DOTACIÓN PARA PERSONAL DE VIGILANCIA Y SEGURIDAD PRIVADA", "image": "product_1.jpg" },...

CodePudding user response:

you can use dynamic import

import React, { useState } from 'react';
import { 
  product_1,
  product_2,
  product_3
} from '../components/utils/Images';
import data from '../assets/data/products.json'

const Catalogo = () => {
  return(
      data.products.map(async(product, index) => {
        const src = await import(`../../assets/image/${product.image}`)
        return (
         <div className='col-3'>
           <Image src={src}/> 
             <Button variant="primary" style={{zIndex:"40"}} onClick={() => counter(index)}>Ver</Button>
         </div>
        )
      })
    
  )
}

export Catalogo
  • Related