Cyberithub

Solved "objects are not valid as a react child" error in React JS

Advertisements

In this article, we will see how to solve "objects are not valid as a react child" error in React.js. If you are a developer who has been working with React JS, then sometimes you might see the error message "objects are not valid as a react child" on your output console. In this article, we will try to understand what causes this error and how we can resolve it with the help of some real world examples. So without further delay, let's begin !!

 

Solved "objects are not valid as a react child" error in React JS

Solved "objects are not valid as a react child" error in React JS

Also Read: Solved "error: cannot find module express" in Node.js

Advertisements

React JS uses JSX to render the final HTML inside the render method. Now we can have both the static as well as the dynamic data to be populated on the front end. Things work very well when the HTML is static on the front end. For this React JS compiler takes the HTML and returns the HMTL template out of it.

But when the render method must parse the dynamic data, the data must be a primitive data type to be printed out on the front end. In case any Javascript object (JSON) has been passed, the React JS compiler would throw the error objects are not valid as a react child. While the issue looks very straightforward, this is one of the most common issues in React JS development.

Advertisements

 

Why React JS render does not Populate objects

Developers love automation these days. Many might raise objections as to why the React render method cannot serialize the object and display it on the front end. If there are multiple keys in an object, the React render method could serialize it and display it on the front end and make the lives of developers easy! React JS render method does not print out, instead raises an error because:-

  • It is not a Serializer. React JS render method has the responsibility of creating HTML, not parsing or serializing Javascript objects.
  • React JS render does not know how to serialize or print out complex data types. For example, // TODO add an example here
  • Having plain text in the final HTML is very necessary. Otherwise, HTML will break at the browser level or create undesirable effects.

Let's try to fix the error by understanding below given example.

Advertisements

 

Example 1: A simple React JS code with Primitive data type

Imagine the below code. This code renders perfectly well on the front end without any errors. Here we print out a variable called myObject on the screen.

import './App.css';
function App() {
  // Some primitive data type
  let myObject = "This is some object"
  // The below code renders perfectly fine
  return (
   <div className="App">
     {/* We print out this object on the screen */}
     {myObject}
   </div>
 );
}
export default App;

 

Example 2: A more Complex example

Now we use a more complex example. Here we print a JSON object called myObject on the screen. There are two keys in the object: name and age. This code will also work completely fine as we are printing out the keys individually. Both the keys are primitive data types hence no error appears.

Advertisements
import './App.css';
function App() {
  // Some primitive data type
  let myObject = { name: "Some name", age: 32}

  // The below code renders perfectly fine
  return (
    <div className="App">
      {/* We print out this object on the screen */}
        <span>{myObject.name}</span><br/> {/* First we print out the name */}
        <span>{myObject.age}</span> {/* Then we print out the age */}
    </div>
  );
}
export default App;

 

Producing the error

Now we print out the whole object instead of individual keys and we get the error!

import './App.css';
function App() {
  let myObject = { name: "Some name", age: 32}
  // The below code throws the error
  return (
    <div className="App">
      {/* We print out the whole object on the screen */}
      <span>{myObject}</span><br/>
    </div>
 );
}
export default App;

We can see the error on the console. This is how it looks like :-

Solved "objects are not valid as a react child" error in React JS 1

If suppose we need to print out this variable, we can create a function that builds the string notation of the variable myObject and return. The return value can be displayed on the screen. We can also create the JSON notation of the object and return:-

import './App.css';
function App() {
  let myObject = { name: "Some name", age: 32}
  // Below method returns the string representation of the object
  let formatMyObject = function() {
    return "Name: " + myObject.name + " - Age: " + myObject.age;
  }

  let jsonSerialize = function() {
    return JSON.stringify(myObject)
  }

  // The below code throws the error
  return (
    <div className="App">
      {/* We print out the whole object on the screen */}
      <span>{formatMyObject()}</span>
      <br/><br/>
      {/* We print out the JSON notation of the object on the screen */}
      <span>{jsonSerialize()}</span>
    </div>
  );
}
export default App;

 

Printing out Lists

Printing out a list of items on the screen is a very common use case. However, this can also trigger the above error. First look at the code producing the error:-

import './App.css';
function App() {

  // Our very simple list
  let myList = [{name: "abc", age: 21}, {name: "xyz", age: 21}]


  // The below code throws the error
  return (
    <div className="App">
       {/* We print out the whole list on the screen */}
       <p>{myList}</p>
    </div>
  );
}
export default App;

To fix this error, we use the map function on the list to iterate over the list and produce the response.

import './App.css';
function App() {

  // Our very simple list
  let myList = [{id: 1, name: "abc", age: 21}, {id: 2, name: "xyz", age: 21}]

  // The below code throws the error
  return (
    <div className="App">
      {/* We print out the whole list on the screen */}
      {
        myList.map( (obj)=> (
         <p>{obj.age + " " + obj.name}</p>
        ))
      }
    </div>
  );
}
export default App;

Using above code will make the "objects are not valid as a react child" error go away. Hope above explanation helped you understood the problem and solved the "objects are not valid as a react child" error.

 

Conclusion

React JS is a lovely framework to work with. However, sometimes very simple code cases can break resulting in an insane amount of time wastage. We looked at one such case where basic rendering on the front end breaks. If you are faced with "objects are not valid as a react child" issue in any of your React JS projects, inspect that primitive datatype is being passed in the render method by looking at the following three-point to being investigated:-

  • Objects are not passed in the React JS render method for any child tag.
  • If you are passing the primitive data type to render in the HTML tag in React render method, ensure that it is not being passed as a JSON It should be passed as a plain object
  • In case a list needs to be populated, make sure to use the map method of Javascript to render the list item as a child.
  • If there is still a need to display multiple keys of a JSON object, create a function that takes the object and returns the formatted/concatenated final primitive value.

Leave a Comment