Categories
React Answers

How to Fix the ‘Objects are not valid as a React child. If you meant to render a collection of children, use an array instead’ Error?

Spread the love

Sometimes, we may encounter the ‘Objects are not valid as a React child. If you meant to render a collection of children, use an array instead’ error when we’re developing our React apps.

In this article, we’ll look at how the ‘Objects are not valid as a React child. If you meant to render a collection of children, use an array instead’ error when we’re developing our React apps.

Fix the ‘Objects are not valid as a React child. If you meant to render a collection of children, use an array instead’ Error

We can fix the ‘Objects are not valid as a React child. If you meant to render a collection of children, use an array instead’ error by rendering an array with the map method or render objects as strings or render the properties individually.

For instance, we can write:

const arr = [1, 2, 3];
export default function App() {
  return (
    <div className="App">
      {arr.map((num) => (
        <div key={num}>{num}</div>
      ))}
    </div>
  );
}

to render the arr array into multiple divs.

We set the key prop to a unique key.

And we render num , which is a number, as the content.

We can only render primitive values directly by putting them between curly braces.

If we have an object, we can render it as a string by writing:

const obj = { foo: 1, bar: 2 };
export default function App() {
  return <div className="App">{JSON.stringify(obj)}</div>;
}

We converted the obj object into a string with JSON.stringify .

Or we can render the properties in the object:

const obj = { foo: 1, bar: 2 };

export default function App() {
  return <div className="App">{obj.foo}</div>;
}

Conclusion

We can fix the ‘Objects are not valid as a React child. If you meant to render a collection of children, use an array instead’ error by rendering an array with the map method or render objects as strings or render the properties individually.

One reply on “How to Fix the ‘Objects are not valid as a React child. If you meant to render a collection of children, use an array instead’ Error?”

Leave a Reply

Your email address will not be published.

If you like the content of this blog, subscribe to my email list to get exclusive articles not available to anyone else.