Objects are not valid as a react child [SOLVED]

You mostly get the error, "Objects are not valid as a react child," when you try to parse an object into JSX. The secret to solving the common error is understanding how JSX works using a relatable example. What is more?

Find out below.

Advertisement

 

Lab Environment Setup

First, let's set up a lab environment to practice solving the common react error: Objects are not valid as a react child.

mkdir react_objects && cd react_objects
npx create-react-app .
code .

We create the project directory called react_objects. We then set up the React library workspace using the create-react-app tool. Lastly, we open the project in Visual Studio Code.

We get the following key file structure.

node_modules

Stores project dependencies.

public folder

Advertisement

Stores files that are public to the browser. The main file is index.html, the only HTML file sent to the browser. React code gets injected into the div element with the root id.

src folder

We mainly write code in the source (src) folder. That includes React components and pages. React comes as complete development and testing package. That is why we get multiple default files in the src folder.

A development environment chiefly requires App.js and index.js. App.js is the primary component. You run other components in it before connecting it with index.js.

index.js grabs the react components and mounts them to the DOM.

import React from 'react';
import ReactDOM from 'react-dom/client';
import './index.css';
import App from './App';

const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(
  <React.StrictMode>
    <App />
  </React.StrictMode>
);

The React.StrictMode monitors the application during development and reports any errors and warnings on the console output. It renders the components from the App component to the DOM. The root variable is a product of ReactDOM, and the div element with the root id.

.gitignore

Helps to ignore development-only, massive, or sensitive files when tracking changes with git.

package.json

Stores the project metadata like name, repository, and package versions.

We can now start a local development server by running the start script.

npm run start
# OR
npm start

Webpack compiles the code and starts a development server on http://localhost:3000.

Advertisement

Objects are not valid as a react child [SOLVED]

That is all we need to create a project to solve the error, "Objects are not valid as a react child." Let's start by decoding the origin of the error.

 

Components and JSX

Components

A typical react application is divided into components. Components are JavaScript functions that return JSX (JavaScript XML).

import logo from './logo.svg';
import './App.css';

function App() {
  return (
    <div className="App">
      <header className="App-header">
        <img src={logo} className="App-logo" alt="logo" />
        <p>
          Edit <code>src/App.js</code> and save to reload.
        </p>
        <a
          className="App-link"
          href="https://reactjs.org"
          target="_blank"
          rel="noopener noreferrer"
        >
          Learn React
        </a>
      </header>
    </div>
  );
}

export default App;

The return block contains JSX. But what exactly is JSX?

 

JSX

We see HTML-like code inside the return block. The (template) code is JSX.

JSX allows us to create HTML-like code before pushing the code to Babel for conversion to actual HTML that gets rendered to the DOM. However, this time, we replace the HTML class attribute with the className keyword because class is a reserved keyword in JavaScript (and JSX is JavaScript, not HTML code).

JSX lets us directly inject JavaScript expressions into the HTML-like tags using curly braces.

Advertisement
function App() {
  const data = "objects are not valid as a react child";
  return (
    <div className="App">
      <h2 className="App-header">The title is { data }. </h2>
    </div>
  );
}

Besides, we put a trailing slash / before a closing tag > of a self-closed HTML tag.

<img src={ logo } className="App-logo" alt="logo" />

React converts the data variable's type into a string before outputting it to the browser. The data type can be of any type except objects and booleans. And that is why you get the error with the message, "objects are not valid as a react child," whenever you try to inject objects into JSX.

Let's see some of the errors and how to correct them.

 

Solved: objects are not valid as a react child

Assume we check whether a writer is one of the people at an event. We mark the writer's presence with a boolean; store her details in an object, and other attendants' names in an array.

function App() {
  const data = "objects are not valid as a react child";
  const isPresent = true;
  const person = {name: "Lorem", likes: "React"};
  const people = ["Lorem", "Ipsum", "Doe"];
  return (
    <div className="App">
      <h2 className="App-header">The title is { data }. </h2>
      <p>It is {isPresent} the writer is present. She is one of these people: { people }.</p>
      <p>Here are her details: { person } </p>
    </div>
  );
}

export default App;

We get a blank page, while the console has an uncaught error:

Objects are not valid as a React child (found: object with keys {name, likes}). 

Objects are not valid as a react child error

What if we comment out the (writer's details) object? Let's give it a try.

Advertisement

Input

function App() {

  const data = "objects are not valid as a react child";
  const isPresent = true;
  // const person = {name: "Lorem", likes: "React"};
  const people = ["Lorem", "Ipsum", "Doe"];

  return (
    <div className="App">
      <h2 className="App-header">The title is { data }. </h2>
      <p>It is {isPresent} the writer is present. She is one of these people: { people }.</p>
      {/* <p>Here are her details: { person } </p> */}
    </div>
  );

}

export default App;

What did you notice?

Output

The page returns some data.

The title is objects are not valid as a react child.
It is the writer is present. She is one of these people: LoremIpsumDoe.

However, we cannot see the output of the isPresent variable because JSX does not know how to convert a boolean into a string.

Objects are not valid as a react child [SOLVED]

The more exciting part is that although the object produced an error, the array elements were printed on the page. So, how can we loop, then print an object's children?

Advertisement

The most straightforward solution is to use an array instead of an object. We can then map the children of the array before pasting each child on the DOM.

Input

function App() {
  const data = "objects are not valid as a react child";
  const isPresent = true;
  const person = ["Lorem", "React"];
  const people = ["Lorem", "Ipsum", "Doe"];
  return (
    <div className="App">
      <h2 className="App-header">The page title is { data }. </h2>
      <p>The writer is {isPresent} and is one of these people: { people }.</p>
      <p> 
        The author has the following details (name, like): 
        { person.map (p => (
          <span key={p}> {p}, </span>
        )) 
      } 
      </p>
    </div>
  );
}

export default App;

We map through the person array, printing its elements into a span element.

We assign the span a key from each element since React needs each mapped array's elements to have a unique key to track its state easily.

Output

The title is objects are not valid as a react child.

It is the writer is present. She is one of these people: LoremIpsumDoe.
The author has the following details (name, like): Lorem, React, 

Objects are not valid as a react child [SOLVED]

Alternatively, we could store the person object in an array and then map the array before decoding the objects. However, for a small object like the one we used in this example, we could directly print the value of its properties without first putting it in an array.

Input

function App() {

  const data = "objects are not valid as a react child";
  const isPresent = true;
  const person = {name:"Lorem", like:"React"};
  const people = ["Lorem", "Ipsum", "Doe"];

  return (
    <div className="App">
      <h2 className="App-header">The title is { data }. </h2>
      <p>It is {isPresent} the writer is present. She is one of these people: { people }.</p>
      <p> The author has the following details: <span> name: {person.name}, like: {person.like} </span> </p>
    </div>
  );

}

export default App;

Output

The title is objects are not valid as a react child.
It is the writer is present. She is one of these people: LoremIpsumDoe.
The author has the following details: name: Lorem, like: React 

Objects are not valid as a react child [SOLVED]

 

Key Takeaway

The most typical cause of the error, "Objects Are not Valid as A React Child," is parsing an object into JSX. As shown in this tutorial, you can solve the error by converting the data into an array or another (primitive) data type except a boolean.

 

Didn't find what you were looking for? Perform a quick search across GoLinuxCloud

If my articles on GoLinuxCloud has helped you, kindly consider buying me a coffee as a token of appreciation.

Buy GoLinuxCloud a Coffee

For any other feedbacks or questions you can either use the comments section or contact me form.

Thank You for your support!!

Leave a Comment

X