0

I have an object like this one:

[
    {
        "periodname": "Test",
        "periodtime": ""
    },
    {
        "periodname": "",
        "periodtime": ""
    }
]

And I want to render a Col for each array inside of it. My React code:

function renderMyPage(props) {

const { myObject } = props

const renderMyPage = () => {
     return [myObject].map((c,i) => {
        return(
            <Col>
              My data here  
            </Col>
          )
       })
    }
}

But I always get only one result, even if I have two or more arrays inside my object.

If I interact again with map or foreach I get the same object. If I use the map function without using "[]" on the object I get an error:

Uncaught TypeError: Cannot read property 'map' of undefined

What I'm doing wrong to get only one result? Tried a lot of other questions around StackOverflow questions but I'm getting the same result.

1 Answer 1

1

As a quick solution try

const renderMyPage = () => {
     return myObject?.map((c,i) => {
        return(
            <Col>
              My data here  
            </Col>
          )
       })
    }
}

or

const renderMyPage = () => {
     if (!myObject) return null;
    
     return myObject.map((c,i) => {
        return(
            <Col>
              My data here  
            </Col>
          )
       })
    }
}
Sign up to request clarification or add additional context in comments.

1 Comment

If you want to tell the TypeScript compiler that you know for sure myObject is defined, you can use return myObject!.map(...

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.