Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Objects are not valid as a React child when I mapping an object

I’m starting react and can’t solve my problem. I have an object

   modes= {
        "easyMode": {
        "field": 5
        },
        "normalMode": {
        "field": 10
        },
        "hardMode": {
        "field": 15
        }
        }

And I need to map this modes(easyMode, normalMode and hardMode), but I know that I can’t map an object, only arrays. Right, but this also doesn’t work

const arrayOfObjects = [{ modes }];

return (
    <ul> {arrayOfObjects.map(mode=> <li key={mode}>{mode} </li>)}</ul>)

How I need to do this right?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

You can use Object.keys() to get an array with modes keys

const modes = {
  easyMode: {
    field: 5,
  },
  normalMode: {
    field: 10,
  },
  hardMode: {
    field: 15,
  },
};

const modesKeys = Object.keys(modes); // ['easyMode','normalMode','hardMode' ]

return (
  <ul> {modesKeys.map(mode => <li key={mode}>{mode}</li>)}</ul>
)
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading