Uncaught error objects are not valid as a react child

The Objects are not valid as a React child error occurs when we try to render the JavaScript Object or a JavaScript Array in the JSX code.
Table of Contents

Hide

  1. Why do we get Objects are not valid as a React child error?
  2. Fix – Objects are not valid as a React child error.
    1. Rendering the Objects
    2. Rendering a Collections of Items
    3. Rendering a Date Object
  3. Conclusion

The Objects are not valid as a React child error occurs when we try to render the JavaScript Object or an Array in the JSX code. 

We can resolve the error by applying the .map() method to an array and returning the JSX for each element of an array. In the case of objects, we need to access their properties and render the data.

Why do we get Objects are not valid as a React child error?

As the error message states, React cannot directly render JavaScript objects or JavaScript Arrays as its children. 

There are a few different things that you have coded wrong in React if you are getting this error.

  1. Rendering an Object directly in JSX code
  2. Rendering a Collection of items directly without using the map() method
  3. Rendering a Date object directly in JSX code
  4. Calling an async function in the JSX code 
  5. Calling a function that returns an object or an invalid child element
  6. Wrapping the variable with double curly {{searchItem.text}} braces instead of single {searchItem.text}

Now that we have understood why we get the error let us try to reproduce the error in the React code with some of the scenarios mentioned above.

import * as React from "react";
export default function NavBar() {

    const headerItems = [
        { id: 1, text: 'Home', href: '/' },
        { id: 2, text: 'JavaScript', href: '/javascript' },
        { id: 3, text: 'React', href: '/react' },
    ];

    const searchItem = {
        text: "Search",
        placeholder: "Search ItsJavaScript",
        autocomplete: true
    }

    const currentDate = new Date()

    return (
        <div>
            {currentDate}
            {headerItems}
            {searchItem}
        </div>
    );

}

Output

Error: Objects are not valid as a React child

Error: Objects are not valid as a React child

Rendering the Objects

React doesn’t support rendering the objects in the JSX code. A JavaScript object is a Non Primitive type, whereas react can render only primitive types inside JSX. 

To solve the issue, we need to access the object properties and render them in the JSX code instead of rendering the object. Also, we need to ensure the child properties of an object are primitive type.

In our example, we had a searchItem object with its own properties such as text, placeholder, and autocomplete. As shown below, we need to access these object properties to render the component properly.

import * as React from "react";
export default function NavBar() {

    const searchItem = {
        text: "Search",
        placeholder: "Search ItsJavaScript",
        autocomplete: true
    }

    return (
        <div>
            <label for="search">{searchItem.text}</label>
            <input type="text" placeholder={searchItem.placeholder} />
        </div>
    );

}

Alternatively, you can also use JSON.stringify() method that converts the entire object into a string before it is rendered.

Rendering a Collections of Items

Rendering a collection in react applications is a common practice widely used to render Navbars, tables, lists, cards, etc.

Like objects, react doesn’t support rendering the Arrays in JSX code. We can solve this by using JavaScript’s .map() method to render a valid react child.

In our example, we have a headerItems that consists of an Array of objects, or we can call it a collection of items. Let us use JavaScript’s map() method to resolve the error.

import * as React from "react";
export default function NavBar() {

    const headerItems = [
        { id: 1, text: 'Home', href: '/' },
        { id: 2, text: 'JavaScript', href: '/javascript' },
        { id: 3, text: 'React', href: '/react' },
    ];

    return (
        <div>
            {headerItems.map((item) => {
                return <a href={item.href}>{item.text}</a>
            })}
        </div>
    );

}

Applying the map() method, it iterates once on each element of an array and returns the JSX for each element. Since each element is an object again here, we cannot directly render an object; instead, we need to access its property to bind the data inside the JSX.

Rendering a Date Object

A Date is an object, and it cannot be rendered directly in JSX; instead, we need to convert it into a string using its methods such as toString() or toLocaleDateString().

import * as React from "react";
export default function NavBar() {

    const currentDate = new Date()

    return (
        <div>
            {currentDate.toString()}
        </div>
    );

}

Conclusion

The Objects are not valid as a React child mainly error occurs when we try to render the JavaScript Object or an Array in the JSX code. The possible scenarios which could lead to this error are as follows.

  • Rendering an Object directly in JSX code
  • Rendering a Collection of items directly without using the map() method
  • Rendering a Date object directly in JSX code
  • Calling an async function in the JSX code 
  • Calling a function that returns an object or an invalid child element
  • Wrapping the variable with double curly {{searchItem.text}} braces instead of single {searchItem.text}

We can fix the issue by applying the .map() method to an array and returning the JSX for each element of an array. In the case of objects, we need to access their properties and render the data and for Date objects, we need to use the built-in methods such as toString() or toLocaleDateString() that returns the date in a string format.

Sign Up for Our Newsletters

Get notified on the latest articles

By checking this box, you confirm that you have read and are agreeing to our terms of use regarding the storage of the data submitted through this form.

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.

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

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.

ALSO READ: insertBefore() JavaScript Method Tutorial

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.

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?

ALSO READ: How to sort by date in JavaScript? [SOLVED]

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.

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.

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.

ALSO READ: Recursive search in array of objects JavaScript? [SOLVED]

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?

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.

ALSO READ: How to convert String to Boolean JavaScript? [SOLVED]

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.

objects are not valid as a react child

Table of Contents
Hide
  1. Introduction
  2. Solution
  3. Live Demo
  4. Live Demo
  5. What if I want to use object as react child since both keys & values are important?
  6. Live Demo
  7. Conclusion

    1. Related Posts

To solve objects are not valid as a react child error, check if the JSX element has javascript object as child, like this –

const jsobj = {"hello" : "world"};

return (
    <div>
        {jsobj}
    </div>
);

then instead of putting object as child, use JSON.stringify() function and convert object into string, like this –

const jsobj = {"hello" : "world"};

return (
    <div>
        {JSON.stringify(jsobj)}
    </div>
);

Introduction

(Jump to solution) I got this strange error, “objects are not valid as a react child” when I was working on my first React Js project. My project was related to a transcription software. This error came up when I was trying to put a JavaScript object inside my JSX.

Check this demo of how react throws error, objects are not valid as a react child

Open Live Demo

Solution

You can not use objects in JSX (What is JSX?). That’s it.

Although, objects can not be used but there are valid ways to use Arrays as a react child.

We generally get response from APIs in JSON. It may contain objects and you might need to show that in jsx. It’s possible.

In our example above, instead of const jsobj = {"hello" : "world"}; if you convert it into array like const jsarr = ["hello", "world"]; then it will work without any issue.

Let’s see this in the code and demo –

const jsarr = ["hello", "world"];
return (
    <div>
        {jsarr}
    </div>
);

Live Demo

Open Live Demo

We can also use an array of JSX as react child. In fact the map() function returns the array only. Like these code examples are perfectly valid –

const jsarr1 = [
  <span style={{color: 'red'}}>This is span 1</span>,
  ' ',
  <span style={{color: 'green'}}>This is span 2</span>,
  <p>This is a paragraph</p>
];

	
const jsarr2 = [1,2,3,4].map(item => {
  return (
    <p key={item}>I am item {item}</p>
  );
});


return (
  <div>
    <div style={{backgroundColor:'lightyellow'}}>{jsarr1}</div>
    <div style={{backgroundColor:'#f0f0f0'}}>{jsarr2}</div>
  </div>
);

Live Demo

Open Live Demo

Sometimes we also get the same error like this – “if you meant to render a collection of children, use an array instead.” It means that either you are using objects or you forgot to enclose your components or JSX elements within a parent. Like this –

return (
    <p>This is paragraph 1</p>
    <p>This is paragraph 2</p>
)

The correct way is –

return (
  <div>
    <p>This is paragraph 1</p>
    <p>This is paragraph 2</p>
  </div>
)

You can also use <React.Fragment></React.Fragment> instead of div. With the newer React versions, you may use <></> too.

You may also like –

convert object to array in javascript to use in for loop

What if I want to use object as react child since both keys & values are important?

There are ways to tackle this problem. You can run your object against map() function and get the required JSX. But remember to first convert object to an array otherwise map will throw an exception. This code will help you –

const obj = {
	"Name": "Akash Mittal",
	"Startup": "StudyWise",
	"Description": "Kids Education App",
	"Link": "https://play.google.com/store/apps/details?id=com.studywise",
};
			
  return (
    <div style={{
        backgroundColor: 'lightyellow', 
        border: '1px solid yellow',
        padding: '10px',
      }}>
      <table>
        <tbody>
        {
          Object.keys(obj).map(itemKey => {
            return (
              <tr key={itemKey}>
                <td>{itemKey}</td>
                <td>{itemKey === 'Link' ? <a href={obj[itemKey]}>{obj[itemKey]}</a> : obj[itemKey]}</td>
              </tr>
            )
          })
        }
        </tbody>
      </table>
    </div>
  );

Live Demo

Open Live Demo

You can pass an object or array as props within components also.

Conclusion

You can’t use Javascript object in JSX directly but you can use arrays. So convert your objects into arrays using map() function.

This is Akash Mittal, an overall computer scientist. He is in software development from more than 10 years and worked on technologies like ReactJS, React Native, Php, JS, Golang, Java, Android etc. Being a die hard animal lover is the only trait, he is proud of.

Related Tags
  • live demo,
  • reactjs,
  • reactjs error

Nearly every developer working in React runs across the error “Objects are not valid as a React child” at some point.

If you are seeing it for the first time, don’t panic! This post will help explain what the error means and how to track down the problem.

Why You’re Seeing the Error

As the error message states, React cannot render objects as children directly. If you are seeing this error, there is a good chance you are trying to render a JS object or collection incorrectly. Here is an example of some invalid children.

import * as React from "react";
export const ExampleComponent: React.FC = () => {
  return (
    <div>
      🛑 Invalid
      <div>{{ foo: 'bar' }} </div>
      <div>{new Date()} </div>
      <div>{['array']} </div>
    </div>
  )
}

React does not try to make any assumptions about how to render objects or a collection. Instead, it is the developer’s job to be more explicit about how they should be rendered.

Debugging the Problem

The “Objects are not valid as a React child” error might mean that a few different things are going wrong.

⚠️ Potential issues: ⚠️
1. Rendering an object (e.g. a JavaScript Date) directly
2. Rendering a collection of items without using a .map()
3. Calling a function that returns an object or other invalid child

This component illustrates the common cases that cause this error as well as examples of valid React children.

import React from "react";
export const Component: React.FC = () => {
  const validChildrenToRender = {
    string: 'string',
    number: 12,
    element: <div>an element!</div>,
    funcThatReturnsValidChild: () => <div>a component!</div>,
  }

  const invalidChildrenToRenderDirectly = {
    object: { something: 'string' },
    array: [{ item: 'item' }],
    date: new Date(),
    funcThatReturnsNonPrimative: () => ({ foo: 'bar' }),
  }
  return (
    <div style={{ width: '100%' }}>
      ✅ Valid
      <div>{validChildrenToRender.string}</div>
      <div>{validChildrenToRender.number}</div>
      <div>{validChildrenToRender.element}</div>
      <div>{validChildrenToRender.funcThatReturnsValidChild()}</div>

      🛑 Invalid
      <div>{invalidChildrenToRenderDirectly.object}</div>
      <div>{invalidChildrenToRenderDirectly.array}</div>
      <div>{invalidChildrenToRenderDirectly.date}</div>
      <div>{invalidChildrenToRenderDirectly.funcThatReturnsNonPrimative()}</div>
    </div>
  )
}

Resolving the Problem

Rendering Objects 📖

React doesn’t know what to do with an object, so you have to tell it exactly how you want it rendered. In this example, there is an object with some details about a book. Instead of rendering book directly, we specify that it should be rendered as the title followed by the author, e.g. “Where the Crawdads Sing by Delia Owens.”

import React from "react";
export const ValidComponent: React.FC = () => {
  const book: Book = { title: "Where the Crawdads Sing", author: "Delia Owens" }
  return (
    <div>
      ✅ Valid
      <div>{book.title} by {book.author}</div>
    </div>
  )
}

Similarly, we call a function that returns some information about the sales of a given book. We can render the output of that function just like we would any other object.

import React from "react";
export const ValidComponent: React.FC = () => {
  const book: Book = { title: "Where the Crawdads Sing", author: "Delia Owens" }
  const getCurrentSalesForBook = (book: Book) => {
    return { 
      salesForCurrentYear: getSalesForCurrentYear(book),
      totalSales: getTotalSales(book)
    }
  )
  return (
    <div>
      ✅ Valid
      <div>{book.title} by {book.author}</div>
      <div>
        This year's sales: ${getCurrentSalesForBook().salesForCurrentYear}
      </div>
    </div>
  )
}

Rendering a Collection of Items 📚

To render a collection, iterate over each item using the .map() method and return a valid React child.

import * as React from "react";
export const ValidComponent: React.FC = () => {
  const array = ["item1", "item2", "item3"]
  return (
    <div>
      ✅ Valid
      <div>
        {array.map((item, i) => (
          <div key={i}>{item}</div>
        ))}
      </div>
    </div>
  )
}

It doesn’t matter what is in your array as long as what you return is a primitive or any valid React child. For example, if you want to render an array of objects, make sure you are explicit about how you want React to render the items. Here is an example to help visualize what this means.

import * as React from "react";
export const ValidComponent: React.FC = () => {
  const groceryList = [
    { name: "Bunch of Kale", quantityNeeded: 1 },
    { name: "Olive oil", quantityNeeded: 1 }
  ];
  return (
    <div>
      ✅ Valid
      <div>
        {groceryList.map((item, i) => (
          <div key={i}>{item.quantityNeeded} {item.name}{</div>
        ))}
      </div>
    </div>
  )
}

In this case, we are telling React to render the grocery list in the format: “1 Bunch of Kale”.

Note: Be sure to add a unique key to each element of an array to help React know which elements have been changed, added or removed. Read more here

Rendering Dates 📆

The simplest approach to resolving invalid rendering of a Date is to use the built in JS .toString() method for Dates. This will convert the Date to a string, which is a primitive, and React will render it without complaint.

import * as React from "react";
export const ValidComponent: React.FC = () => {
  return (
    <div>
      ✅ Valid
      <div>{(new Date).toString()}</div>
    </div>
  )
}

You’ll likely want to have better formatting for Dates than simply converting it to a string. There are various JS date libraries that can help you with this. Check out date-fns and Moment.js as a good starting point.

Remember that React throws an “Objects are not valid as a React child” error instead of making assumptions about how to render objects. The next time you see this error, make sure you are only rendering primitives. Read the stack trace carefully to get a sense of where the issue is coming from in your code. Happy React coding!

Introduction

While writing React applications, you may have come across the error message «objects are not valid as a react child.» This error is a common one, especially when we’re just starting out with React and JSX code. It’s thrown when you try to directly render an object in JSX, instead of using a valid React child such as a string, number, or React element.

Consider code like this:

export default function Dashboard() {
    const staff = [
        {name: 'Billy', role: 'admin'},
        {name: 'Sally', role: 'contributor'}
    ];
    
    const hq = {
        state: 'Nebraska',
        country: 'USA',
    };
    
    return (
      <>
          <span>{staff}</span>
          <div>
              {hq}
          </div>
      </>
    );
}

In the code example above, the error is thrown because we are trying to render the staff and hq objects directly inside the <span> and <div> elements. Since objects (including arrays) are not valid React children, this will throw a error «Objects are not valid as a React child».

To fix this error, we need to convert the objects into valid React children before rendering them. In this case, we can use the .map() method to iterate over each item of an array and render it as a React element.

Here’s an example of how we can fix the code above to avoid the «objects are not valid as a react child» error:

import React from 'react';

export default function App() {
    const staff = [
        {name: 'Billy', role: 'admin'},
        {name: 'Sally', role: 'contributor'}
    ];

    const hq = {
        state: 'Nebraska',
        country: 'USA',
    };

    return (
        <div>
            {staff.map(user => (
                <div key={user.name}>
                    <p>{user.name}</p>
                    <p>{user.role}</p>
                </div>
            ))}
            
            <h1>HQ</h1>
            <p>State: {hq.state}</p>
            <p>Country: {hq.country}</p>
        </div>
    );
}

In the code above, we use the .map() method to iterate over each object in the list and render it as an HTML element. This allows us to «break out» the object to properly construct it as valid HTML. Otherwise React doesn’t know how to render a JavaScript object, which is why it throws the error.

For a simple object like hq, we can access each property individually and specify the HTML rendering for each element.

Conclusion

The «objects are not valid as a react child» error is thrown when you try to pass an object directly to a React component as a prop or child. To fix this error, you need to convert the array, for example, into a valid React child by iterating over its values and rendering them as React elements. This will allow React to render the object as part of the component’s output, without throwing an error.

Понравилась статья? Поделить с друзьями:
  • Uncaught error no url provided dropzone
  • Uncaught error no element is specified to initialize perfectscrollbar
  • Uncaught error map container is already initialized
  • Uncaught error createroot target container is not a dom element
  • Uncaught error invalidstateerror the connection has not been established yet