I have the following codes that was supposed to render data from a json file. It doesn’t display me anything, except the h1 with the curly braces, instead of the data wanted. here is the code:
import prod from "../../data/produtos.json";
export default function Produto(props) {
return (
<figure>
<img src={prod.imagem}></img>
<figcaption>(prod.titulo)</figcaption>
<p>(prod.preco)</p>
<button className="btn"> Adicionar ao carrinho </button>
</figure>
);
}
import "./Produtos.css"
import productions from "../data/produtos.json";
import Produto from "./Produto";
import { useState } from "react";
export default function Produtos(props) {
const [lista, setLista] = useState(productions);
return (
<div className="produtos">
{lista.map((product) => (
<div className="Products">
<Produto id={product.id} {...product} />
</div>
))}
</div>
);
}
[
{
"id": 1,
"titulo": "",
"preco": 16.9,
"imagem": "../public/imagens/pwero.jpg"
},
{
"id": 2,
"titulo": "",
"preco": 26.89,
"imagem": "../public/imagens/oepw.jpg"
},
{
"id": 3,
"titulo": "",
"preco": 17.4,
"imagem": "../public/imagens/ewer.jpg"
},
{
"id": 4,
"titulo": "",
"preco": 2.2,
"imagem": "/////w"
},
{
"id": 5,
"titulo": "",
"preco": 49.99,
"imagem": ""
},
{
"id": 6,
"titulo": "",
"preco": 5.99,
"imagem": "zzzzys"
}
]
=
it should be rendering the json data. I don’t know if the problem is in the map. The json file is imported right in both components.
3
Answers
try adding a
return
statement in the map.Here is the snippet for the code :
In
Produto
, you need to accessprops
(notprod
) and use curly brackets{}
. You should not be importing/loading any JSON at this point.I would initialize the
lista
state with an empty array and use an effect to either fetch it (recommended), or load it from the JSON file. Also, if you useArray.prototype.map
, you should supply akey
prop.You could alternatively load the JSON asynchronously.
1- You don’t need to import the data into your Produto component. Its code should be :
Instead of putting the js instructions in
parentheses ()
, you must instead put them inbraces {}
2- As far as the
Produtos
component is concerned, all you have to do is pass the product as an attribute of the Produto component