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

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.

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.

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

One error that you might encounter when working with React is:

Uncaught Error: Objects are not valid as a React child

This error occurs when you use a vanilla JavaScript object inside JSX directly.

This tutorial will show you examples that cause this error and how to fix it.

1. Embedding an object in JSX causes this error

To understand why this error occurs, suppose you have a vanilla JavaScript object that you pass into a component as follows:

const userData = { name: "John", age: 21 };

function App() {
  return <div>{userData}</div>;
}

The above code embeds the userData object inside the App component’s JSX syntax.

React doesn’t know what to render when provided with an object. Do you want to render the whole object as a string? Or do you want to render the values only?

This is why instead of assuming something, React throws an error:

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

React can only render primitive types like a string, a number, or a boolean.

To fix this error, you need to add more details in your JSX code on how to render the object you provided.

For example, you might want to render the object values, so you can improve the code like this:

const userData = { name: "John", age: 21 };

function App() {
  return (
    <div>
      {userData.name}: {userData.age}
    </div>
  );
}

The above code renders John: 21 to the screen.

As an alternative, you might want to render the key and the value in multiple div tags.

You need to use the entries() and map() functions as shown below:

const userData = { name: "John", age: 21 };

function App() {
  return Object.entries(userData).map(([key, value]) => (
    <div key={key}>
      {key}: {value}
    </div>
  ));
}

The rendered App component would be similar to this:

<div id="root">
  <div>name: John</div>
  <div>age: 21</div>
</div>

If you want to render the whole object to the screen, you need to use JSON.stringify to convert the object to a string first.

Since a string is a primitive type, React will render it as-is without any modifications:

const userData = { name: "John", age: 21 };

function App() {
  return <div>{JSON.stringify(userData)}</div>
}

React will render {"name":"John","age":21} to the screen with the above code.

2. Rendering an array of objects

The same error occurs when you try to render an array of objects without telling React how to render it.

Suppose you pass an array of objects to React component as follows:

const users = [
  { name: "John", age: 21 },
  { name: "Jane", age: 20 },
  { name: "Lisa", age: 24 },
];

function App() {
  return <div>{users}</div>;
}

React again won’t know how to handle the given users array.

To fix this error, you can use the map() function and render the array values as shown below:

const users = [
  { name: "John", age: 21 },
  { name: "Jane", age: 20 },
  { name: "Lisa", age: 24 },
];

function App() {
  return (
    <div>
      {users.map(user => (
        <p>
          {user.name}: {user.age}
        </p>
      ))}
    </div>
  );
}

Output:

<div>
  <p>John: 21</p>
  <p>Jane: 20</p>
  <p>Lisa: 24</p>
</div>

As you can see, the map() function comes in handy when you need to render an array of objects.

3. Don’t convert your primitive type into an object

This error also occurs when you mistakenly convert a primitive type into an object using curly braces.

Suppose you have a name variable that you want to render as follows:

const name = "John"

function App() {
  return <div> {{name}} </div>
}

The error happens because there are two sets of curly braces {{}} surrounding the name variable. These curly braces convert the name variable into an object as {name: 'John'}.

You need to fix the code by using only one set of curly braces:

const name = "John"

function App() {
  return <div> {name} </div>
}

When you run the application again, notice the error doesn’t appear.

Conclusion

React shows “Objects are not valid as a React child” error when you attempt to pass a JavaScript object inside JSX directly.

As React doesn’t know how you want the object to be presented on the screen, it chooses to show an error and render nothing instead. To fix this error, you need to tell React how to render the object by adding more code to the component.

This tutorial has shown you three common causes for this error and the solution for each error.

I hope this tutorial is helpful. Happy coding! 🙌

Возможно, вам также будет интересно:

  • Object reference not set to an instance of an object код ошибки 9 перевод
  • Object reference not set to an instance of an object как исправить ошибку
  • Object reference not set to an instance of an object cities skylines ошибка
  • Object progressevent как устранить эту ошибку
  • Object of type response has no len ошибка

  • Понравилась статья? Поделить с друзьями:
    0 0 голоса
    Рейтинг статьи
    Подписаться
    Уведомить о
    guest

    0 комментариев
    Старые
    Новые Популярные
    Межтекстовые Отзывы
    Посмотреть все комментарии