How to Pretty Print JSON with ReactJS

Pretty printing JSON in ReactJS means displaying JSON data in a human-readable format, with indentation and proper spacing. This can be achieved using built-in JavaScript functions and React components. Here is a step-by-step guide to do this in detail:

Step 1. Create a React Component

First, you need a React component where you will display the JSON data. This can be a functional or class component. For this example, we will use a functional component.

Step 2. Use JSON.stringify for Pretty Printing

The JSON.stringify function can be used to convert a JavaScript object into a JSON string. To pretty-print, you pass additional arguments for spacing.

Step 3. Display the Pretty Printed JSON

Use a <pre> tag to preserve whitespace and formatting, and a <code> tag for code semantics.

Step-by-Step Code Example

Here’s the complete example:

Step 1. Setup React Environment

If you haven’t set up a React project, you can use Create React App:

npx create-react-app json-pretty-print
cd json-pretty-print
npm start

Step 2. Create PrettyPrintJSON Component

Create a new file named PrettyPrintJSON.js in the src directory:

import React from 'react';

// Sample JSON data
const data = {
  name: "John Doe",
  age: 30,
  address: {
    street: "123 Main St",
    city: "Anytown",
    state: "CA"
  },
  hobbies: ["reading", "traveling", "swimming"]
};

const PrettyPrintJSON = ({ jsonData }) => {
  const prettyJSON = JSON.stringify(jsonData, null, 2);

  return (
    <pre>
      <code>
        {prettyJSON}
      </code>
    </pre>
  );
};

const App = () => {
  return (
    <div>
      <h1>Pretty Print JSON Example</h1>
      <PrettyPrintJSON jsonData={data} />
    </div>
  );
};

export default App;

Step 3. Update index.js to Render the Component

In your src/index.js, ensure you are rendering the App component:

import React from 'react';
import ReactDOM from 'react-dom';
import './index.css';
import App from './App';

ReactDOM.render(
  <React.StrictMode>
    <App />
  </React.StrictMode>,
  document.getElementById('root')
);

Step 4. Add Basic Styling

You can add some basic styling to make the JSON look better. Update src/index.css:

pre {
  background-color: #f5f5f5;
  padding: 10px;
  border-radius: 5px;
  overflow: auto;
  max-height: 400px; /* or any value you prefer */
}

code {
  font-family: 'Courier New', Courier, monospace;
  color: #333;
}

Explanation

  1. JSON Data: The sample JSON data is defined as a constant data object.
  2. Component Structure: The PrettyPrintJSON component takes jsonData as a prop.
  3. Pretty Printing: Inside the component, JSON.stringify(jsonData, null, 2) is used to convert the JSON object into a string with 2-space indentation for readability.
  4. HTML Structure: The JSON string is placed inside a <pre> and <code> tag to preserve formatting and apply code semantics.
  5. Styling: Basic CSS is applied to the <pre> and <code> tags for better readability and to handle overflow.

Dynamic JSON Data

If you want to dynamically pretty-print JSON data (e.g., from an API or user input), you can modify the component to accept props or state:

import React, { useState } from 'react';

const PrettyPrintJSON = ({ jsonData }) => {
  const prettyJSON = JSON.stringify(jsonData, null, 2);

  return (
    <pre>
      <code>
        {prettyJSON}
      </code>
    </pre>
  );
};

const App = () => {
  const [data, setData] = useState({
    name: "John Doe",
    age: 30,
    address: {
      street: "123 Main St",
      city: "Anytown",
      state: "CA"
    },
    hobbies: ["reading", "traveling", "swimming"]
  });

  return (
    <div>
      <h1>Pretty Print JSON Example</h1>
      <PrettyPrintJSON jsonData={data} />
      {/* Add logic here to update `data` dynamically, e.g., fetch from API */}
    </div>
  );
};

export default App;

Conclusion

By following this guide, you can easily pretty-print JSON data in ReactJS, making it more readable and manageable in your applications. This approach is flexible enough to handle static and dynamic JSON data.

Up Next
    Ebook Download
    View all
    Learn
    View all