Home » How To Fix Objects Are Not Valid as a React Child Error

How To Fix Objects Are Not Valid as a React Child Error

how to fix objects are not valid as a react child error

Today in this blog post, we are going to fix objects are not valid as a react child error in React JS. Nearly all React developers may have encountered the error “Objects not valid as a React child” at one time or another.

We get this when we try to directly render an array or object in our JSX code. The map() method can be used to render arrays and access properties of the object inside our JSX.

function App() {
  const myList = [
    { id: "1", label: "Javascript" },
    { id: "2", label: "React JS" },
    { id: "3", label: "Next JS" },
  ];

  const myObj = { id: "1", label: "Javascript" };

  return (
    <div>
      {/* Trying to render list of objects */}
      <div>{myList}</div>

      {/* Trying to render an Object */}
      <div>{myObj}</div>
    </div>
  );
}

export default App;

In the above code, we are rendering a list of objects and an object directly inside the JSX code. This will cause the “Objects not valid as a React child” error in React.

objects are not valid as a react child error

How To Fix Objects Are Not Valid as a React Child Error in React JS

To solve this error, we are going to use the map() method to render our list inside JSX.

To render an Object we have to tell React exactly how we want it to be rendered. In this example, there is an object called myObj with some details. Instead of rendering the myObj directly. we need to specify how the object needs to be rendered.

function App() {
  const myList = [
    { id: "1", label: "Javascript" },
    { id: "2", label: "React JS" },
    { id: "3", label: "Next JS" },
  ];

  const myObj = { id: "4", label: "Python" };

  return (
    <div>
      {/* rendering list of objects using map() method */}
      {myList.map((item, index) => {
        return <div key={index}>{item.id} - {item.label}</div>;
      })}

      {/* rendering Object data*/}
      <div>{myObj.id} - {myObj.label}</div>
    </div>
  );
}

export default App;

This error may also occur when we try to render the Date object directly. To fix it, we need to convert the date object to a string.

function App() {

  const todayDate = new Date()

  return (
    <>
      <div>{todayDate.toString()}</div>

      <div>{todayDate.toLocaleDateString()}</div>
    </>
  );
}

export default App;

To do that we can use the toString() method or toLocaleDateString() method to convert the Date object to a string.

Hope this post was helpful.

Also check out:

Tags:

Leave a Reply

Your email address will not be published.