invariant violation: objects are not valid as a react child

  • Last Update :
  • Techknowledgy :

TLDR; (From the source below) : Make sure all of the items you're rendering in JSX are primitives and not objects when using React. This error usually happens because a function involved in dispatching an event has been given an unexpected object type (i.e passing an object when you should be passing a string) or part of the JSX in your component is not referencing a primitive (i.e. this.props vs this.props.name). I was having this error and it turned out to be that I was unintentionally including an Object in my JSX code that I had expected to be a string value: was just that I was passing an object with keys specified in the error while trying to render the object directly in a component using {object} expecting it to be a string

This is our Splunktool team suggestion ✌, we tried and its working fine
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>
    );
​
}
2._
return (
    <BreadcrumbItem href={routeString}>
        {breadcrumbElement}
    </BreadcrumbItem>
)

So I got this error when trying to display the createdAt property which is a Date object. If you concatenate .toString() on the end like this, it will do the conversion and eliminate the error. Just posting this as a possible answer in case anyone else ran into the same problem:

{
   this.props.task.createdAt.toString()
}

Suggestion : 2

The React.js error "Objects are not valid as a React child" occurs when we try to directly render an object or an array in our JSX code. To solve the error, use the map() method to render arrays or access properties on the object in your JSX code. Another common cause of the "Objects are not valid as a React child" error is trying to directly render a Date object in our JSX code. The React error "Objects are not valid as a React child" occurs for multiple reasons: The issue is that we are trying to directly render an array or an object in our JSX code.

1._
Copied!export default function App() {
  const employees = [
    {id: 1, name: 'Alice', country: 'Austria'},
    {id: 2, name: 'Bob', country: 'Belgium'},
    {id: 3, name: 'Carl', country: 'Canada'},
  ];

  const obj = {
    id: 4,
    name: 'Dean',
    country: 'Denmark',
  };

  // ⛔️ Uncaught Error: Objects are not valid as a React child (found: object with keys {id, name, country}).
  // If you meant to render a collection of children, use an array instead.

  return (
    <div>
      {employees}

      {obj}
    </div>
  );
}
2._
Copied!export default function App() {
  const employees = [
    {id: 1, name: 'Alice', country: 'Austria'},
    {id: 2, name: 'Bob', country: 'Belgium'},
    {id: 3, name: 'Carl', country: 'Canada'},
  ];

  const obj = {
    id: 4,
    name: 'Dean',
    country: 'Denmark',
  };

  return (
    <div>
      {employees.map((employee, index) => {
        return (
          <div key={index}>
            <h2>name: {employee.name}</h2>
            <h2>country: {employee.country}</h2>

            <hr />
          </div>
        );
      })}

      <hr />
      <hr />
      <hr />

      <div>
        <h2>name: {obj.name}</h2>
        <h2>county: {obj.country}</h2>
      </div>

      <hr />
    </div>
  );
}
3._
Copied!export default function App() {
  const employees = [
    {id: 1, name: 'Alice', country: 'Austria'},
    {id: 2, name: 'Bob', country: 'Belgium'},
    {id: 3, name: 'Carl', country: 'Canada'},
  ];

  const obj = {
    id: 4,
    name: 'Dean',
    country: 'Denmark',
  };

  return (
    <div>
      <h4>{JSON.stringify(employees)}</h4>

      <h4>{JSON.stringify(obj)}</h4>
    </div>
  );
}
5._
Copied!export default function App() {
  return (
    <div>
      <h4>{date.toLocaleDateString()}</h4>
    </div>
  );
}
6._
Copied!export default function App() {
  const message = 'hello world';

  // ⛔ Objects are not valid as a React child (found: object with keys {message}).
  return (
    <div>
      <h4>{{message}}</h4>
    </div>
  );
}

Suggestion : 3

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. 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! The “Objects are not valid as a React child” error might mean that a few different things are going wrong.

1._
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>
  )
}

⚠️ 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>
  )
}

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>
  )
}

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>
  )
}

Suggestion : 4

If you execute the following code in your react application, you will see the following error in the browser console: Objects are not valid as a React child (found: object with keys ...). If you meant to render a collection of children, use an array instead. If you use the following code to display the date, you will receive the same error: If you are having a separate function to display the data and you are sending the values in a object and receiving them as shown below, you will face the same issue:

1._
function App() {
  const name = { first: "John", last: "Doe" }

  return <div className="App">{name}</div>
}

export default App
2._
function App() {
  const name = { first: "John", last: "Doe" }

  return (
    <div className="App">
      {name.first} {name.last}
    </div>
  )
}

export default App
3._
function App() {
  const date = new Date()

  return <div className="App">{date}</div>
}

export default App
5._
function App() {
  const counter = 10

  return <div className="App">{{ counter }}</div>
}

export default App
6._
function App() {
  const counter = 10

  return <div className="App">{counter}</div>
}

export default App

Suggestion : 5

“Invariant Violation: Modal.render(): A valid React element (or null) must be returned. You may have returned undefined, an array or some other invalid object.” If I remove the insertRow attribute, the error goes away, and the component will render again. I have upgraded a React app from 15.6.2 to 16.0.0, and updated react-boostrap-table too. Hi Allen, I think I was using the latest version - I had been going through all my dependencies and updating them. I will try again and let you know.

If my JSX looks like:

<BootstrapTable
   ref="licenceTypesTable"
   insertRow={true}
   data={this.props.licenceTypesData.licenceTypes}
   striped={true} 
   hover={true}
   options={options}
   search={true}
   exportCSV={true}>
      <TableHeaderColumn dataField="id" isKey={true} autoValue={true}>ID</TableHeaderColumn>
      <TableHeaderColumn dataField="title" dataSort={true}>Type</TableHeaderColumn>
</BootstrapTable>

Then it fails to render.

I get this console message:

Invariant Violation: Objects are not valid as a React child(found: object with keys {
   $$typeof,
   key,
   children,
   containerInfo,
   implementation
}).If you meant to render a collection of children, use an array instead.
in Modal
   in div in ToolBar in div in div in BootstrapTable in div in div in div

I was relying on insertRow to provide UI to add new data, it would be a shame to have to roll my own.

It is helps, licenceTypes is a very simple array:

licenceTypes: [{
   id: 1,
   title: "MIT"
}, {
   id: 2,
   title: "Apache-2.0"
}]

Suggestion : 6

As we have seen, a large number of examples were utilised in order to solve the React Native - Invariant Violation: Objects Are Not Valid As A React Child Solution problem that was present. React Native - Invariant Violation: Objects Are Not Valid As A React Child Solution In this article, the solution of React Native - Invariant Violation: Objects Are Not Valid As A React Child Solution will be demonstrated using examples from the programming language.

fetchDataOrderNo = async () => {
   const response = await fetch("http://192.168.254.105:3308/OrderNo/order_no")
   const json = await response.json()
   this.setState({
      orderDet: json[0].order_no
   })
}