Company logo
  • Empleos
  • Bootcamp
  • Acerca de nosotros
  • Para profesionales
    • Inicio
    • Empleos
    • Cursos y retos
    • Preguntas
    • Profesores
    • Bootcamp
  • Para empresas
    • Inicio
    • Nuestro proceso
    • Planes
    • Pruebas
    • Nómina
    • Blog
    • Calculadora

0

170
Vistas
Iterating over object and displaying as table - React.js

I have an object:

{
  cities: { 
    MCR: "Manchester",
    LDN: "London",
    NYC: "New York"
  }
}

and I want to iterate over these and display them in a table format which will show the city code and the long name next to it. Something like:

 <tbody>
          <tr>
            <th>City Code</th>
            <th>City Name</th>
          </tr>
            <tr>
              {Object.entries(cities).map(([key, value]) => {
                <>
                <td>{key}</td>
                <td>{value}</td>
                </>
              }
            )}
          </tr>
    </tbody>

However this doesn't display anything and also shows an error when hovering over value:

Type 'unknown' is not assignable to type 'ReactNode'.ts(2322)

I'm quite new to React and wondering how best to display this information?

Thanks

7 months ago · Juan Pablo Isaza
3 Respuestas
Responde la pregunta

0

let say you have an object as:

  const obj = {
    cities: {
      MCR: "Manchester",
      LDN: "London",
      NYC: "New York"
    }
  };

It would be better to loop over cities and create a new tr so that It looks like a table

CODESANDBOX LINK

You want to map over the cities then you should return it from map as:

<tbody>
      <tr>
        <th>City Code</th>
        <th>City Name</th>
      </tr>
      { Object.entries( obj.cities ).map( ( [key, value] ) => {
        return (   // PROBLEM SHOULD RETURN
          <tr>
            <td>{ key }</td>
            <td>{ value }</td>
          </tr>
        );
      }
      ) }
    </tbody>
7 months ago · Juan Pablo Isaza Denunciar

0

You need to return the result in each iteration. Also, each iteration would return a tr with a key prop:

{
  Object.entries(obj.cities).map(([key, value]) => (
    <tr key={key}>
      <td>{key}</td>
      <td>{value}</td>
    </tr>
  ))
}

Note: since city is a key in an object, you'll need to access it as above

7 months ago · Juan Pablo Isaza Denunciar

0

You are just missing the return in your map's callback function. Always remember to include a return in your arrow functions when using it like this: () => {}. It is easy to miss because ()=>() would return whatever you write in the second () but in the former example this is not true.

7 months 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 empleo Planes Nuestro proceso Comercial
Legal
Términos y condiciones Política de privacidad
© 2023 PeakU Inc. All Rights Reserved.