Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

262
Visualizações
REACT JS How can I convert that to as a component?
const ItemList = () => {

    fetch('http://localhost:3001/api/itemList/', {
        method: "POST",
        headers: {
            "Content-Type": "application/json",
            "Accept": "application/json",
        },
        body: JSON.stringify({
            userId: localStorage.getItem("userId"),
        })
    }).then(res => res.json())

        .then(data => {
            data = data.map(item => {
                console.log(item);
                return (
                    document.getElementById('cards').innerHTML +=
                    `<div class="card" style="width: 18rem;">
                    <img src="${item.imagePath}" class="card-img-top" alt="..." />
                    <div class="card-body">
                        <h5 class="card-title">${item.itemName}</h5>
                        <p class="card-text">${item.tag}</p>
                    </div>
                </div>`

              

I have a data for push to front with cards. I just found this way works with cards but I want to use Cards component for make it better.

If I convert innerHTML part to that:

                return (
                    document.getElementById('cards').innerHTML +=
                    <Card style={{ width: '18rem' }}>
                        <Card.Img variant="top" src={item.imagePath} />
                        <Card.Body>
                            <Card.Title>{item.itemName}</Card.Title>
                            <Card.Text>
                                {item.tag}
                            </Card.Text>
                        </Card.Body>
                    </Card>
                )

I am getting as a output

[object Object][object Object][object Object][object Object]

Where I am making mistake? and how can I push to front this json data with cards?

Example json data


{ "id": 1, "itemName": "sadasd", "itemImagePath": "pngwing.com.png", "userID": "117961395738439786389", "tags": [ "tags", "ts" ], "createdAt": "2022-06-15T00:27:42.958Z", "updatedAt": "2022-06-15T00:27:42.958Z" }

about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

Just remove the document.getElementById('cards').innerHTML +=. You don't want that. ReactJS should do the DOM update. And, you should not return from the fetch function. Create a state, and you can use it to render the JSX.. Here is the properly structured Functional Component for you.

import { useEffect, useState } from "react";

const ItemList = () => {
  const [item, setItem] = useState({});

  useEffect(() => {
    fetch("http://localhost:3001/api/itemList/", {
      method: "POST",
      headers: {
        "Content-Type": "application/json",
        Accept: "application/json",
      },
      body: JSON.stringify({
        userId: localStorage.getItem("userId"),
      }),
    })
      .then((res) => res.json())
      .then((data) => {
        setItem(data);
      });
  }, []);

  return (
    <>
      {item && Object.keys(item).length > 0 && (
        <Card style={{ width: "18rem" }}>
          <Card.Img variant="top" src={item.imagePath} />
          <Card.Body>
            <Card.Title>{item.itemName}</Card.Title>
            <Card.Text>{item.tag}</Card.Text>
          </Card.Body>
        </Card>
      )}
    </>
  );
};

export default ItemList;

Here, I used the useEffect hook to fetch the items when the component is mounted on DOM. And we are verifying if the item object is not empty before rendering

about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda