React Error: Objects are not valid as a React child while adding to DOM node

Viewed 30

It outputs the data in correct format while outputting into console. But while adding to DOM it gives below error, Error: Objects are not valid as a React child (found: object with keys {street, suite, city, zipcode, geo}). If you meant to render a collection of children, use an array instead.

import React from "react";
    export default class Fetch extends React.Component {
      constructor() {
        super();
        this.state = { dataList: [] };
      }
    
      async componentDidMount() {
        let data = await fetch("https://jsonplaceholder.typicode.com/users");
    
        if (data.ok) {
          var fetchedData = await data.json();
          this.setState({ dataList: fetchedData });
        } else console.log("Error");
      }
    
      render() {
        return (
          <table>
            {this.state.dataList.map((item) => {
              return (
                <tr key={item.id}>
                  <td>{item.id}</td>
                  <td>{item.name}</td>
                  <td>{item.username}</td>
                  <td>{item.email}</td>
                  <td>{item.address}</td>
                </tr>
              );
            })}
          </table>
        );
      }
    }
1 Answers

The issue is in the line <td>{item.address}</td>, the item.address is further a JSON with further deep key-value pairs.

"address": {
  "street": "Kulas Light",
  "suite": "Apt. 556",
  "city": "Gwenborough",
  "zipcode": "92998-3874",
  "geo": {
    "lat": "-37.3159",
    "lng": "81.1496"
  }
}

A solution here can be to stringify it using {JSON.stringify(item.address)} and print it, does the job but it will be ugly, manually using each key explicitly is acceptable.

Related