Home » Reactjs » Invariant Violation: Objects are not valid as a React child

Invariant Violation: Objects are not valid as a React child

Posted by: admin November 29, 2017 Leave a comment

Questions:

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

Answers:

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.

Questions:
Answers:

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

Questions:
Answers:

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.

Questions:
Answers:

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, changing the return() section to:

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

Fixed the problem

Questions:
Answers:

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

Questions:
Answers:

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

import React, { Component } from 'react';
import PropTypes from 'prop-types';

class SCT extends Component {
    constructor(props, context) {
        super(props, context);
        this.state = {
            data: this.props.data,
            new_data: {}
        };
    }
    componentDidMount() {
        let new_data = this.state.data;
        console.log(`new_data`, new_data);
        this.setState(
            {
                new_data: Object.assign({}, new_data)
            }
        )
    }
    render() {
        return (
            <div>
                this.state.data = {JSON.stringify(this.state.data)}
                <hr/>
                <div style={{color: 'red'}}>
                    {this.state.new_data.name}<br />
                    {this.state.new_data.description}<br />
                    {this.state.new_data.dependtables}<br />
                </div>
            </div>
        );
    }
}

SCT.propTypes = {
    test: PropTypes.string,
    data: PropTypes.object.isRequired
};

export {SCT};
export default SCT;
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>

Questions:
Answers:

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!

Leave a Reply

Your email address will not be published. Required fields are marked *