Skip to content

How to fix ‘Objects are not valid as a react child’ error?

React is one of the most popular web development libraries around at the moment. The framework depends heavily on Javascript, a language previously only used for implementing logic in web pages.

While it’s quite advantageous using React to build your websites or web apps, it can also be a bit of a headache if you don’t follow the rules. In this article, we’re looking at the “Objects are not valid as a React child” error, its causes and what you can do to fix the problem. 

Also read: React vs Next.js: 3 talking points


What causes this error?

While the error doesn’t precisely state what you’re doing wrong, it clearly states the rule that’s being broken. You can’t use objects as a child in React, meaning you’re most likely doing at least one of the following.

  • Rendering an object directly.
  • Rendering a collection of objects without map()
  • Calling a function that is returning an object or other invalid child.

How to fix this?

You can try out the following x fixes. 

Rendering objects

If you have to render an object in the DOM, try rendering it using properties instead of rendering the entire object. 

import React from "react";
export const Component = () => {
  const validObject: Car = { title: "Chevy", owner: "Camaro" }
  return (
    <div>
      <div>{Car.title} by {Car.owner}</div>
    </div>
  )
}
What is Metadata? Types and benefits | Candid.Technology
Photo by Shahadat Shemul

Rendering a collection

To render a collection, you’ll have to loop over every item using the map() function. Here’s how.

import React from "react";
export const Component = () => {
  const array = ["item1", "item2", "item3"]
  return (
    <div>
      <div>
        {array.map((item, i) => (
          <div key={i}>{item}</div>
        ))}
      </div>
    </div>
  )
}

You’ll have to follow the same approach if you’re using data from a database like MySQL or MongoDB. Do keep in mind that React (and Next.js) requires you to mention a unique key to know which elements have been added, removed or changed.


Converting objects to strings

Another thing you can do when you’re trying to render an object in the DOM is to use the toString function to convert your object data type to a string. Here’s an example

import React from "react";
export const Component = () => {
  return (
    <div>
      <div>{(new Date).toString()}</div>
    </div>
  )
}

In the example mentioned above, we’ve converted a date object to a string using the toString() method. This allows us to render the object in the DOM without any errors whatsoever.

Also read: How to fix ‘React-scripts: Command not found’ error?

Hello There!

If you like what you read, please support our publication by sharing it with your friends, family and colleagues. We're an ad-supported publication. So, if you're running an Adblocker, we humbly request you to whitelist us.







>