N Kaushik

How to print or show JSON data in a React component

September 29, 2021

How to print or show JSON data in a React component:

Sometimes, we need to print the JSON data directly in a component in React. This is required mostly for debugging purposes.

You can’t directly print JSON object to a react component.

For example,

import "./styles.css";

const jsonData = {
  "name": "Alex",
  "age" : 20,
  "info": {
    "selected": false,
    "qualification": {
      "documents": "doc"
    }
  }
}
export default function App() {
  return (
    <div className="App">
     {jsonData}
    </div>
  );
}

In this example, I am trying to print jsonData to the component.

It will throw the following error:

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

Instead, we can use JSON.stringify:

import "./styles.css";

const jsonData = {
  "name": "Alex",
  "age" : 20,
  "info": {
    "selected": false,
    "qualification": {
      "documents": "doc"
    }
  }
}
export default function App() {
  return (
    <div className="App">
     {JSON.stringify(jsonData)}
    </div>
  );
}

It will show the JSON value in the component.

JSON print react component


Subscribe to my Newsletter