score:9

Accepted answer

In your productList component you are using a promise instead of rendering child, to overcome this you can make it a stateful component fix this like:

import React, { Component } from 'react';
import Product from "./Product/index";

class ProductList extends Component {
  constructor(props) {
    super(props)
    this.state = {
      goods: []
    }
  }

  componentDidMount = () => {
    import("../../../data/data.json")
      .then(json => this.state({ goods: json.goods }))
  }

  render() {
    const { goods } = this.state
    return (
      <div>
        {goods.map(image => <div><Product images={image.pictures} /></div>)}
      </div>
    )
  }
}

export default ProductList;

or alternatively you can import it in beginning like:

import React from 'react';
import Product from "./Product/index";
import goods from "../../../data/data.json"

const ProductList = () => {
  const renderedGoods = goods.map(image => {
    return <div><Product images={image.pictures} /></div>
  })
  return <div>{renderedGoods}</div>
}

export default ProductList;

Not an issue, yes you resolved the promise correct,

but as even when you type in console what you are actually returning is a promise and .then or .catch are callbacks called when its either resolved or rejected so you see react wants is something to render and you cannot render a promise

score:1

Close - move the import to the top of file:

import myData from "../../../data/data.json";

Then change your rendered list to this:

const renderedList = myData.goods.map(image => (<div><Product images={image.pictures} /></div>));

score:2

It works but why you are importing json data use axios insted of import. Axios documentation

Your component will look like

import React, { Component } from 'react';
import axios from 'axios';
import Product from "./Product/index";

class ProductList extends Component {
  constructor(props) {
    super(props)
    this.state = {
      products: []
    }
  }

  componentDidMount = () => {
    axios.get("products.json").then(json => {
        this.setState({ products: json.data.goods });
    });
  }

  render() {
    const { products } = this.state
    return (
      <div>
        {products.map(image => <div><Product images={image.pictures} /></div>)}
      </div>
    )
  }
}

export default ProductList;

Keep your json or data file inside public folder

I hope this works for you

score:2

Just use map or filter function as the Array you are trying to render is an array of Objects and those Objects can't be rendered due to multiple re-rendering and hence React DOM won't allow that .


Related Query

More Query from same tag