[javascript] Invariant Violation: Objects are not valid as a React child

In my component's render function I have:

render() {
    const items = ['EN', 'IT', 'FR', 'GR', 'RU'].map((item) => {
      return (<li onClick={this.onItemClick.bind(this, item)} key={item}>{item}</li>);
    });
    return (
      <div>
        ...
                <ul>
                  {items}
                </ul>
         ...
      </div>
    );
  }

everything renders fine, however when clicking the <li> element I receive the following error:

Uncaught Error: Invariant Violation: Objects are not valid as a React child (found: object with keys {dispatchConfig, dispatchMarker, nativeEvent, target, currentTarget, type, eventPhase, bubbles, cancelable, timeStamp, defaultPrevented, isTrusted, view, detail, screenX, screenY, clientX, clientY, ctrlKey, shiftKey, altKey, metaKey, getModifierState, button, buttons, relatedTarget, pageX, pageY, isDefaultPrevented, isPropagationStopped, _dispatchListeners, _dispatchIDs}). If you meant to render a collection of children, use an array instead or wrap the object using createFragment(object) from the React add-ons. Check the render method of Welcome.

If I change to this.onItemClick.bind(this, item) to (e) => onItemClick(e, item) inside the map function everything works as expected.

If someone could explain what I am doing wrong and explain why do I get this error, would be great

UPDATE 1:
onItemClick function is as follows and removing this.setState results in error disappearing.

onItemClick(e, item) {
    this.setState({
      lang: item,
    });
}

But I cannot remove this line as I need to update state of this component

This question is related to javascript reactjs

The answer is


Typically this pops up because you don't destructure properly. Take this code for example:

const Button = text => <button>{text}</button>

const SomeForm = () => (
  <Button text="Save" />
)

We're declaring it with the = text => param. But really, React is expecting this to be an all-encompassing props object.

So we should really be doing something like this:

const Button = props => <button>{props.text}</button>

const SomeForm = () => (
  <Button text="Save" />
)

Notice the difference? The props param here could be named anything (props is just the convention that matches the nomenclature), React is just expecting an object with keys and vals.

With object destructuring you can do, and will frequently see, something like this:

const Button = ({ text }) => <button>{text}</button>

const SomeForm = () => (
  <Button text="Save" />
)

...which works.

Chances are, anyone stumbling upon this just accidentally declared their component's props param without destructuring.


React child(singular) should be type of primitive data type not object or it could be JSX tag(which is not in our case). Use Proptypes package in development to make sure validation happens.

Just a quick code snippet(JSX) comparision to represent you with idea :

  1. Error : With object being passed into child

    <div>
    {/* item is object with user's name and its other details on it */}
     {items.map((item, index) => {
      return <div key={index}>
    --item object invalid as react child--->>>{item}</div>;
     })}
    </div>
    
  2. Without error : With object's property(which should be primitive, i.e. a string value or integer value) being passed into child.

    <div>
     {/* item is object with user's name and its other details on it */}
      {items.map((item, index) => {
       return <div key={index}>
    --note the name property is primitive--->{item.name}</div>;
      })}
    </div>
    

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

Source - codingbismuth.com


I got this error rendering something in a ternary operator. What I did:

render(){
  const bar = <div>asdfasdf</div>
  return ({this.state.foo ? {bar} : <div>blahblah</div>})
}

Turns out it should be bar without the brackets, like:

render(){
  const bar = <div>asdfasdf</div>
  return ({this.state.foo ? bar : <div>blahblah</div>})
}

For those who mentioned Stringify() and toString() as solution, I will say that worked for me but we have to understand the problem and why did it occur. In my code it was simple issue. I had 2 buttons which call same function but one button was not passing the argument to that function properly.


I too was getting this "Objects are not valid as a React child" error and for me the cause was due to calling an asynchronous function in my JSX. See below.

class App extends React.Component {
    showHello = async () => {
        const response = await someAPI.get("/api/endpoint");

        // Even with response ignored in JSX below, this JSX is not immediately returned, 
        // causing "Objects are not valid as a React child" error.
        return (<div>Hello!</div>);
    }

    render() {
        return (
            <div>
                {this.showHello()}
            </div>
        );
    }
}

What I learned is that asynchronous rendering is not supported in React. The React team is working on a solution as documented here.


My issue was very particular: in my .env file, I put a comment in the line that had my api url:

API_URL=https://6ec1259f.ngrok.io #comment

I'd get the Invariant violation error when trying to log in/sign up, as the api url was wrong.


try{
    throw new Error(<p>An error occured</p>)
}catch(e){
    return (e)
}

The above code produced the error, I then rewrote it like this:

try{
    throw(<p>An error occured</p>)
}catch(e){
    return (e)
}

Take note of the removal of new Error() in the try block...

A better way to write the code in order to avoid this error message Expected an object to be thrown no-throw-literal is to pass a string into throw new Error() instead of JSX and return JSX in your catch block, something like this:

try{
    throw new Error("An error occurred")
}catch(e){
    return (
        <p>{e.message}</p>
    )
}

Just thought I would add to this as I had the same problem today, turns out that it was because I was returning just the function, when I wrapped it in a <div> tag it started working, as below

renderGallery() {
  const gallerySection = galleries.map((gallery, i) => {
    return (
      <div>
        ...
      </div>
    );
  });
  return (
    {gallerySection}
  );
}

The above caused the error. I fixed the problem by changing the return() section to:

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

...or simply:

return gallerySection

This was my code:

class App extends Component {
  constructor(props){
    super(props)
    this.state = {
      value: null,
      getDatacall : null
    }
    this.getData = this.getData.bind(this)
  }
  getData() {
  //   if (this.state.getDatacall === false) {
    sleep(4000)
    returnData("what is the time").then(value => this.setState({value, getDatacall:true}))
    // }
  }
  componentDidMount() {
    sleep(4000)

    this.getData()
  }
  render() {
    this.getData()
    sleep(4000)
    console.log(this.state.value)
    return (
      <p> { this.state.value } </p>
    )
  }
}

and I was running into this error. I had to change it to

 render() {
    this.getData()
    sleep(4000)
    console.log(this.state.value)
    return (
      <p> { JSON.stringify(this.state.value) } </p>
    )
  }

Hope this helps someone!


Mine had to do with forgetting the curly braces around props being sent to a presentational component:

Before:

const TypeAheadInput = (name, options, onChange, value, error) => {

After

const TypeAheadInput = ({name, options, onChange, value, error}) => {

I got this error any time I was calling async on a renderItem function in my FlatList.

I had to create a new function to set my Firestore collection to my state before calling said state data inside my FlatList.


My issue was simple when i faced the following error:

objects are not valid as a react child (found object with keys {...}

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

object: {
    key1: "key1",
    key2: "key2"
}

while rendering on a React Component, I used something like below

render() {
    return this.props.object;
}

but it should have been

render() {
    return this.props.object.key1;
}

I got the same error, I changed this

export default withAlert(Alerts)

to this

export default withAlert()(Alerts).

In older versions the former code was ok , but in later versions it throws an error. So use the later code to avoid the errror.


In my case the error was happening because I returned elements array in curly braces instead of just returning the array itself.

Code with error

   render() {
        var rows = this.props.products.map(product => <tr key={product.id}><td>{product.name}</td><td>{product.price}</td></tr>
        );
        return {rows};
    }

Correct code

render() {
    var rows = this.props.products.map(product => <tr key={product.id}><td>{product.name}</td><td>{product.price}</td></tr>
    );
    return rows;
}

Thanks to a comment by zerkms, I was able to notice my stupid mistake:

I had onItemClick(e, item) when I should have had onItemClick(item, e).


If using stateless components, follow this kind of format:

const Header = ({pageTitle}) => (
  <h1>{pageTitle}</h1>
);
export {Header};

This seemed to work for me


For anybody using Firebase with Android, this only breaks Android. My iOS emulation ignores it.

And as posted by Apoorv Bankey above.

Anything above Firebase V5.0.3, for Android, atm is a bust. Fix:

npm i --save [email protected]

Confirmed numerous times here https://github.com/firebase/firebase-js-sdk/issues/871


Found: object with keys

Which means you passing something is a key-value. So you need to modify your handler:

from
onItemClick(e, item) {
   this.setState({
     lang: item,
   });
}
to
onItemClick({e, item}) {
  this.setState({
    lang: item,
  });
}

You missed out the braces ({}).


If for some reason you imported firebase. Then try running npm i --save [email protected]. This is because firebase break react-native, so running this will fix it.


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:

return (
    <BreadcrumbItem href={routeString}>
        {breadcrumbElement}
    </BreadcrumbItem>
)

breadcrumbElement used to be a string but due to a refactor had become an Object. Unfortunately, React's error message didn't do a good job in pointing me to the line where the problem existed. I had to follow my stack trace all the way back up until I recognized the "props" being passed into a component and then I found the offending code.

You'll need to either reference a property of the object that is a string value or convert the Object to a string representation that is desirable. One option might be JSON.stringify if you actually want to see the contents of the Object.


In case of using Firebase, if it doesn't work by putting at the end of import statements then you can try to put that inside one of the life-cycle method, that is, you can put it inside componentWillMount().

componentWillMount() {
    const firebase = require('firebase');
    firebase.initializeApp({
        //Credentials
    });
}

I just got the same error but due to a different mistake: I used double braces like:

{{count}}

to insert the value of count instead of the correct:

{count}

which the compiler presumably turned into {{count: count}}, i.e. trying to insert an Object as a React child.


I also have the same problem but my mistake is so stupid. I was trying to access object directly.

class App extends Component {
    state = {
        name:'xyz',
        age:10
    }
    render() {
        return (
            <div className="App">
                // this is what I am using which gives the error
                <p>I am inside the {state}.</p> 

                //Correct Way is

                <p>I am inside the {this.state.name}.</p> 
            </div>
        );
    }                                                                             

}

If in case your using Firebase any of the files within your project. Then just place that import firebase statement at the end!!

I know this sounds crazy but try it!!


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

Mine had to do with unnecessarily putting curly braces around a variable holding a HTML element inside the return statement of the render() function. This made React treat it as an object rather than an element.

render() {
  let element = (
    <div className="some-class">
      <span>Some text</span>
    </div>
  );

  return (
    {element}
  )
}

Once I removed the curly braces from the element, the error was gone, and the element was rendered correctly.


Try this

 {items && items.title ? items.title : 'No item'}

Invariant Violation: Objects are not valid as a React child happened to me when using a component that needed a renderItem props, like:

renderItem={this.renderItem}

and my mistake was to make my renderItem method async.


In my case it was i forgot to return a html element frm the render function and i was returning an object . What i did was i just wrapped the {items} with a html element - a simple div like below

_x000D_
_x000D_
<ul>{items}</ul>
_x000D_
_x000D_
_x000D_


I just put myself through a really silly version of this error, which I may as well share here for posterity.

I had some JSX like this:

...
{
  ...
  <Foo />
  ...
}
...

I needed to comment this out to debug something. I used the keyboard shortcut in my IDE, which resulted in this:

...
{
  ...
  { /* <Foo /> */ }
  ...
}
...

Which is, of course, invalid -- objects are not valid as react children!


I had the same problem because I didn't put the props in the curly braces.

export default function Hero(children, hero ) {
    return (
        <header className={hero}>
            {children}
        </header>
    );
}

So if your code is similar to the above one then you will get this error. To resolve this just put curly braces around the props.

export default function Hero({ children, hero }) {
    return (
        <header className={hero}>
            {children}
        </header>
    );
}

  1. What's happening is the onClick function you are trying to implement gets executed immediately.

  2. As our code is not HTML it is javascript so it is interpreted as a function execution.

  3. onClick function takes a function as argument not an function execution.

const items = ['EN', 'IT', 'FR', 'GR', 'RU'].map((item) => { return (<li onClick={(e) => onItemClick(e, item)} key={item}>{item}</li>); });

this will define an onClick function on List Item that will get executed after clicking on it not as soon as our component renders.


Obviously, as others have mentioned previously in this thread, in React JSX props.children cannot be of type Object. This is NOT the root cause for the issue in your specific question.

If you carefully read the error text, you will see that React has produced the error while trying to render an Object that matches the signature of a SyntheticEvent:

Uncaught Error: Invariant Violation: Objects are not valid as a React child (found: object with keys {dispatchConfig, dispatchMarker, nativeEvent, target, currentTarget, type, eventPhase, bubbles, cancelable, timeStamp, defaultPrevented, isTrusted, view, detail, screenX, screenY, clientX, clientY, ctrlKey, shiftKey, altKey, metaKey, getModifierState, button, buttons, relatedTarget, pageX, pageY, isDefaultPrevented, isPropagationStopped, _dispatchListeners, _dispatchIDs}). If you meant to render a collection of children, use an array instead or wrap the object using createFragment(object) from the React add-ons. Check the render method of Welcome.

However, one wonders why you are trying to render a SyntheticEvent, and this is where the real answer to your question resides. You obviously have no intention of rendering a SyntheticEvent, but you've got your event handler parameters out of order.

In your render method, you are binding the onItemClick event handler to the this of your class component and passing in item as an argument:

render() {
    const items = ['EN', 'IT', 'FR', 'GR', 'RU'].map((item) => {
      return (<li onClick={this.onItemClick.bind(this, item)} key={item}>{item}</li>);
    });
// ...

According to the documentation for Function.prototype.bind, all arguments passed after the thisArg are prepended to any arguments subsequently passed when the target function is later invoked:

arg1, arg2, ...

Arguments to prepend to arguments provided to the bound function when invoking the target function.

If we then look at the event handler, we see that the parameter e is listed before the parameter item.

onItemClick(e, item) {
    this.setState({
      lang: item,
    });
}

When onItemClick(e, item) is invoked, the item passed in during the bind invocation will precede the triggering event, so parameter e will be set to the mapped and bound item, and parameter item will be set to the event.

When setState is called, lang will be set to the SyntheticEvent representing the triggering onClick event, and when you try to render the value in this.state.lang elsewhere, you will receive the Invariant Violation error you've seen.


I'd like to add another solution to this list.

Specs:

  • "react": "^16.2.0",
  • "react-dom": "^16.2.0",
  • "react-redux": "^5.0.6",
  • "react-scripts": "^1.0.17",
  • "redux": "^3.7.2"

I encountered the same error:

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

This was my code:

let payload = {
      guess: this.userInput.value
};

this.props.dispatch(checkAnswer(payload));

Solution:

  // let payload = {
  //   guess: this.userInput.value
  // };

this.props.dispatch(checkAnswer(this.userInput.value));

The problem was occurring because the payload was sending the item as an object. When I removed the payload variable and put the userInput value into the dispatch everything started working as expected.


Something like this has just happened to me...

I wrote:

{response.isDisplayOptions &&
{element}
}

Placing it inside a div fixed it:

{response.isDisplayOptions &&
    <div>
        {element}
    </div>
}

My error was because of writing it this way:

props.allinfo.map((stuff, i)=>{
  return (<p key={i}> I am {stuff} </p>)
})



instead of:

props.allinfo.map((stuff, i)=>{
  return (<p key={i}> I am {stuff.name} </p>)
})

It meant I was trying to render object instead of the value within it.

edit: this is for react not native.


In my case it was because of a dynamic array which had to be injected at runtime.

I just added the null checks for object and it worked fine.

Before:

...
render(
...
    <div> {props.data.roles[0]} </div>
...
);

After:

...
let items = (props && props.data && props.data.roles)? props.data.roles: [];
render(
...
    <div> {items[i]} </div>
...
);

If you are using Firebase and seeing this error, it's worth to check if you're importing it right. As of version 5.0.4 you have to import it like this:

import firebase from '@firebase/app'
import '@firebase/auth';
import '@firebase/database';
import '@firebase/storage';

Yes, I know. I lost 45 minutes on this, too.


I have the same issue, in my case, I update the redux state, and new data parameters did not match old parameters, So when I want to access some parameters it through this Error,

Maybe this experience help someone


You were just using the keys of object, instead of the whole object!

More details can be found here: https://github.com/gildata/RAIO/issues/48

_x000D_
_x000D_
import React, { Component } from 'react';_x000D_
import PropTypes from 'prop-types';_x000D_
_x000D_
class SCT extends Component {_x000D_
    constructor(props, context) {_x000D_
        super(props, context);_x000D_
        this.state = {_x000D_
            data: this.props.data,_x000D_
            new_data: {}_x000D_
        };_x000D_
    }_x000D_
    componentDidMount() {_x000D_
        let new_data = this.state.data;_x000D_
        console.log(`new_data`, new_data);_x000D_
        this.setState(_x000D_
            {_x000D_
                new_data: Object.assign({}, new_data)_x000D_
            }_x000D_
        )_x000D_
    }_x000D_
    render() {_x000D_
        return (_x000D_
            <div>_x000D_
                this.state.data = {JSON.stringify(this.state.data)}_x000D_
                <hr/>_x000D_
                <div style={{color: 'red'}}>_x000D_
                    {this.state.new_data.name}<br />_x000D_
                    {this.state.new_data.description}<br />_x000D_
                    {this.state.new_data.dependtables}<br />_x000D_
                </div>_x000D_
            </div>_x000D_
        );_x000D_
    }_x000D_
}_x000D_
_x000D_
SCT.propTypes = {_x000D_
    test: PropTypes.string,_x000D_
    data: PropTypes.object.isRequired_x000D_
};_x000D_
_x000D_
export {SCT};_x000D_
export default SCT;
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>
_x000D_
_x000D_
_x000D_


Just create a valid JSX element. In my case I assigned a component to an object.

const AwesomeButtonComponent = () => <button>AwesomeButton</button>
const next = {
  link: "http://awesomeLink.com",
  text: "Awesome text",
  comp: AwesomeButtonComponent
}

Somewhere else in my Code I wanted to dynamically assign that button.

return (
  <div>
    {next.comp ? next.comp : <DefaultAwesomeButtonComp/>}
  </div>
)

I solve this by declaring a JSX comp which I initialized via the props comp.

const AwesomeBtnFromProps = next.comp
return (
  <div>
    {next.comp ? <AwesomeBtnFromProps/> : <DefaultAwesomeButtonComp/>}
  </div>
)

In my case, I added a async to my child function component and encountered this error. Don't use async with child component.