Home > Blockchain >  How to return a react component with the for in statement?
How to return a react component with the for in statement?

Time:02-12

I'm trying to iterate over a nested object with the for..in statement an return text component for each object iterated over.

const animals = {
  "cat": Object {
    "number": 0,
  },
  "dog": Object {
    "number": 1,
  }
{ 
      for(let item in animals) {
        for(let property in animals[item]){
          return (
            <Text>{item}</Text>
            <Text>{animals[item][property]}</Text>
          )
      }
    }
}

As you see above, I tried to wrap the function in curly brackets in hopes of using jsx to render the components much like one would do with .map, but I got a slew of errors, so I'm pretty sure this incorrect.

My Linter says Expression expected for the two for(s) and the return ().

I can console.log item, and animals[item][property] so I am confident everything outside the return () is correct.

How would I go about correctly returning the Text elements?

CodePudding user response:

You have to use react fragment, like this

<>
<Text>{item}</Text>
<Text>{animals[item][property]}</Text>
</>

CodePudding user response:

Honestly, this code makes no sense to me.

You have for loop about the object inside an object? Is that some new syntax or what?

  • Related