Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

258
Views
REACT JS ¿Cómo puedo convertir eso en un componente?
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>`

Tengo un dato para empujar al frente con tarjetas. Acabo de encontrar que esta forma funciona con tarjetas, pero quiero usar el componente Tarjetas para mejorarlo.

Si convierto la parte innerHTML a eso:

 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> )

estoy obteniendo como salida

[objeto Objeto][objeto Objeto][objeto Objeto][objeto Objeto]

¿Dónde estoy cometiendo un error? y ¿cómo puedo impulsar estos datos json con tarjetas?

Ejemplo de datos json

 { "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 answers
Answer question

0

Simplemente elimine document.getElementById('cards').innerHTML += . No quieres eso. ReactJS debería hacer la actualización de DOM. Y, no debe regresar de la función de fetch . Cree un estado y puede usarlo para representar el JSX.. Aquí está el Functional Component correctamente estructurado para usted.

 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;

Aquí, utilicé el gancho useEffect para obtener los elementos cuando el componente está montado en DOM . Y estamos verificando si el item del elemento no está vacío antes de renderizar

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!