Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

200
Vistas
cómo agregar encabezados a la respuesta api usando reactjs

Soy nuevo en reaccionar js, tengo una pantalla de inicio con barra de búsqueda. donde el usuario recupera la información de un empleado al proporcionar la identificación. aquí está el código para eso.

 const [firstNames, setFirstNames] = useState(""); <input value={name} type="text" id="header-search" placeholder="Enter the search term" name={'id'} onChange={handleChange} /> <button onClick={HandleSearch}>Search</button> const handleChange= (e) => { e.preventDefault(); setName(e.target.value); } const HandleSearch = e => { e.preventDefault(); axios.get(`http://localhost:8080/search?id=`+name) .then(response => { setLoading(false); if(response.status == 200 && response != null){ console.log("RES",response.data); var tmpArray= []; var tmpJsx =[]; // I was checking to see if I could retrieve the data from my response. var dataparse = response.data; var length = dataparse.length; console.log("length of my response array is: "+length) //printing the elements in array for (var i=0; i< length; i++){ //console.log(response.data[i].firstname); setFirstNames((firstNames) => [...firstNames, response.data[i]]); } } else{ console.log('problem fetching'); } }) .catch(error => { setLoading(false); console.log("error occured: "+error); }); }

y aquí está mi función de retorno:

 {firstNames.map(function (names, index) { return ( <tr key={index}> <td> {names.firstname} -</td> <td> {names.lastname}</td> </tr> ) })}

¿Cómo agrego los encabezados a estos datos? por ejemplo

 firstname lastname abc abclast

Traté de poner esto en la función de mapa, pero luego mis datos se veían así:

 firstname lastname abc abclast firstname lastname def deflast firstname lastname ghi ghilast

Estoy seguro de que hay algo que me falta, ¿alguien podría ayudarme a lograrlo? Gracias.

 firstname lastname abc abclast def deflast ghi ghilast
about 4 years ago · Juan Pablo Isaza
1 Respuestas
Responde la pregunta

0

Puede hacer una representación condicional comprobando si la matriz tiene una longitud superior a 0

Un ejemplo sería así. Puede aplicar de manera similar a su problema

 let names = [ {firstName: 'John',lastName: 'Cena'}, {firstName: 'Rey',lastName: 'Mysterio'}, ] const App = props => { return ( <div> {names.length > 0 && <table> //table renders only when array has elements <tbody> <tr> <th>First Name</th> //setting headers <th>Last Name</th> </tr> {names.map((name,index) => { //mapping for individual rows return ( <tr key={index}> <td>{name.firstName}</td> <td>{name.lastName}</td> </tr> ) })} </tbody> </table>} </div> ); };

demostración de Codesandbox

about 4 years ago · Juan Pablo Isaza Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda