Home > Software engineering >  Iterating over object and displaying as table - React.js
Iterating over object and displaying as table - React.js

Time:07-03

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

CodePudding user response:

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>

CodePudding user response:

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

CodePudding user response:

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.

  • Related