1

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

3 Answers 3

2

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>
Sign up to request clarification or add additional context in comments.

Comments

1

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

Comments

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.