Jonny
Jonny

Reputation: 1283

Using nested objects in React state

Objects are not valid as a React child (). If you meant to render a collection of children, use an array

I receive the above error and I don't fully understand the limitations of what it's telling me. Here is my code that is giving me this error, I have an object where one of the properties has the value of an array of objects:

state = {
    clubs: [{
        teamName: something,
        gamesPlayed: [{
            homeTeam: someName,
            awayTeam: someNameElse,
            score: numbers
        },
        {
            homeTeam: ...
            ... etc
        }]
    }]
}

The element that renders the code:

function RenderTest(props) {
    return (
        <ul>
            <li>
                <div>
                    <ul style={{paddingLeft: 10+'px'}}>
                        {props.clubs.map( (key, i) => (
                            <li>
                                <div>Team: {key.teamName} ID: {key.teamId}</div> <-- works as expected
                                <div>Games Played: {key.gamesPlayed.home}</div> <-- throws the error
                            </li>
                        ))}
                    </ul>
                </div>
            </li>
        </ul>
    )
}

Does it mean that I cannot have a nested object like this? It seems a bit limiting. It seems logical that I store the data like this - clubs is an array of objects, each one a football team with their games played that season.

Thank you

Upvotes: 0

Views: 130

Answers (1)

Peter Lehnhardt
Peter Lehnhardt

Reputation: 4985

When you write

<div>Games Played: {key.gamesPlayed.home}</div>

you basically tell react to create a div element with exactly two children:

  1. The string 'Games Played: ',
  2. Whatever key.gamesPlayed.home stores, in this case it is an array (Which is basically just an object in javascript)!

React on the other side requires, that children of any components must be either a string or another component. An array is none of that. So in order to make it work, you have to loop over the array and render the respective part of each array element. A short example from my side to replace above code snipped would be

<div>
  {key.gamesPlayed.map(game => (
    <div>{game.homeTeam}</div>
  )}
</div>

(Assuming game.homeTeam is a string!)

Upvotes: 1

Related Questions