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 abclastTraté 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 ghilastEstoy seguro de que hay algo que me falta, ¿alguien podría ayudarme a lograrlo? Gracias.
firstname lastname abc abclast def deflast ghi ghilastPuede 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> ); };