Ways to Display JSON in React

Working with APIs is a huge part of my daily life as a React developer. Often, I need to show raw data to users or internal teams in a way that isn’t a mess.

I have spent years building dashboards for US-based logistics and financial firms. One thing I’ve learned is that nobody likes looking at a giant wall of unformatted text.

In this tutorial, I will show you exactly how to implement a React JSON viewer component. These methods will help you turn ugly data strings into clean, interactive trees.

JSON Viewer in Your React App

When I first started, I used to dump data into a <div>. It was impossible to read and even harder to debug.

A dedicated viewer allows your users to expand or collapse nodes. This is essential when dealing with large datasets, such as US Census data or complex financial records.

Method 1: Use the Built-in JSON.stringify Method

If you want a quick solution without installing any extra packages, this is my go-to move. It is perfect for simple debugging or basic internal tools.

I often use this when I’m building a quick prototype for a client in New York or Chicago and need to verify the API response immediately.

The trick here is to use the third argument of the JSON.stringify function. This adds the indentation that makes the data readable.

import React from 'react';

const SimpleJsonViewer = () => {
  // Sample data: US Tech Company Employee Record
  const employeeData = {
    id: "EMP-9920",
    name: "James Anderson",
    location: {
      city: "San Francisco",
      state: "California",
      timezone: "PST"
    },
    roles: ["Senior Engineer", "Team Lead"],
    active: true,
    salary_range: "$150,000 - $180,000"
  };

  return (
    <div style={{ padding: '20px', backgroundColor: '#f4f4f4' }}>
      <h2>Employee Data (Raw Preformatted)</h2>
      <pre style={{ 
        textAlign: 'left', 
        backgroundColor: '#282c34', 
        color: '#abb2bf', 
        padding: '15px', 
        borderRadius: '5px',
        overflowX: 'auto'
      }}>
        {JSON.stringify(employeeData, null, 2)}
      </pre>
    </div>
  );
};

export default SimpleJsonViewer;

You can see the output in the screenshot below.

Display JSON in React

While this works, it isn’t interactive. You cannot collapse the sections, which leads us to more robust libraries.

Method 2: Implement react-json-view

In my experience, react-json-view is the most popular choice for professional React apps. It is highly customizable and looks great out of the box.

I recently used this for a project involving US Real Estate listings. We needed to show the metadata for different properties in a clean, searchable format.

First, you will need to install it via npm: npm install react-json-view

import React from 'react';
import ReactJson from 'react-json-view';

const ProfessionalJsonViewer = () => {
  // Sample data: US Real Estate Market Insight
  const marketData = {
    region: "Pacific Northwest",
    stats: {
      median_home_price: 750000,
      currency: "USD",
      cities: [
        { name: "Seattle", zip_codes: [98101, 98102, 98104] },
        { name: "Portland", zip_codes: [97201, 97205] }
      ]
    },
    inventory_low: true,
    last_updated: "2024-05-10T14:30:00Z"
  };

  return (
    <div style={{ padding: '20px' }}>
      <h1>Market Analysis Data</h1>
      <div style={{ border: '1px solid #ddd', borderRadius: '8px', padding: '10px' }}>
        <ReactJson 
          src={marketData} 
          theme="monokai"
          displayDataTypes={false}
          enableClipboard={true}
          collapsed={1}
        />
      </div>
    </div>
  );
};

export default ProfessionalJsonViewer;

You can see the output in the screenshot below.

Ways to Display JSON in React

I love this library because it includes a “Copy to Clipboard” feature automatically. This saves so much time for users who need to grab specific ID strings.

Method 3: Use react-json-tree for a Minimalist Look

Sometimes, the “Monokai” look of the previous method is too heavy. If I am building a clean, white-label dashboard, I prefer react-json-tree.

It is based on the Redux DevTools styling. It feels very lightweight and integrates well with modern UI kits like Tailwind or Material UI.

Install it using: npm install react-json-tree

import React from 'react';
import { JSONTree } from 'react-json-tree';

const MinimalistJsonViewer = () => {
  // Sample data: US E-commerce Order Summary
  const orderDetails = {
    order_id: "ORD-77654",
    customer: {
      first_name: "Sarah",
      last_name: "Miller",
      email: "sarah.m@example.us"
    },
    shipping_address: {
      street: "123 Liberty Ave",
      city: "Philadelphia",
      state: "PA",
      zip: "19106"
    },
    items: [
      { sku: "IPHONE-15-PRO", price: 999 },
      { sku: "CASE-MAGSAFE", price: 49 }
    ],
    tax_exempt: false
  };

  const theme = {
    scheme: 'monokai',
    author: 'wimer hazenberg (http://www.monokai.nl)',
    base00: '#ffffff', // White background
    base0B: '#4caf50', // Green for values
    base0D: '#2196f3'  // Blue for keys
  };

  return (
    <div style={{ padding: '20px' }}>
      <h2>Customer Order Details</h2>
      <JSONTree data={orderDetails} theme={theme} invertTheme={false} />
    </div>
  );
};

export default MinimalistJsonViewer;

This method is perfect if you want to customize the colors to match your specific brand guidelines.

Method 4: Create a Custom Collapsible JSON Component

I have found that some high-security projects don’t allow third-party libraries for data display. In those cases, I build a simple recursive component.

It isn’t as hard as it sounds. We just need a component that calls itself if the value is an object or an array.

import React, { useState } from 'react';

const JsonNode = ({ data, label }) => {
  const [isExpanded, setIsExpanded] = useState(true);
  const isObject = data !== null && typeof data === 'object';

  return (
    <div style={{ marginLeft: '20px', fontFamily: 'monospace' }}>
      <div onClick={() => setIsExpanded(!isExpanded)} style={{ cursor: isObject ? 'pointer' : 'default' }}>
        {isObject && (isExpanded ? '▼ ' : '▶ ')}
        <strong>{label}:</strong> {!isObject && ` ${String(data)}`}
      </div>
      {isObject && isExpanded && (
        <div>
          {Object.entries(data).map(([key, value]) => (
            <JsonNode key={key} label={key} data={value} />
          ))}
        </div>
      )}
    </div>
  );
};

const CustomJsonViewer = () => {
  // Sample data: US Weather Alert Data
  const weatherData = {
    station: "KNYC - Central Park",
    coordinates: [40.7812, -73.9665],
    current: {
      temp_f: 72,
      condition: "Partly Cloudy",
      humidity: "45%"
    },
    alerts: ["No active alerts for New York County"]
  };

  return (
    <div style={{ padding: '20px', border: '1px solid #ccc' }}>
      <h2>Live Weather Feed</h2>
      <JsonNode label="Root" data={weatherData} />
    </div>
  );
};

export default CustomJsonViewer;

You can see the output in the screenshot below.

React Display JSON

This gives you total control. You can add custom icons, specific CSS-in-JS logic, or even logging features whenever a node is clicked.

Handle Large Data Sets

I have worked on projects where the JSON response was several megabytes. Displaying all of that at once will crash the browser.

When dealing with massive US healthcare records or financial ledgers, I always use virtualization.

If you expect huge files, I recommend looking into react-window combined with your JSON viewer. This ensures only the visible rows are rendered in the DOM.

Choose the Right Method

In most cases, react-json-view is the winner. It handles almost everything you need for a standard US-based SaaS application.

If you are just doing a quick check, stick to Method 1 with pre tags. It is fast and requires zero maintenance.

I hope you found this tutorial helpful! Using a proper viewer component makes your application feel much more professional and user-friendly.

You may also read:

51 Python Programs

51 PYTHON PROGRAMS PDF FREE

Download a FREE PDF (112 Pages) Containing 51 Useful Python Programs.

pyython developer roadmap

Aspiring to be a Python developer?

Download a FREE PDF on how to become a Python developer.

Let’s be friends

Be the first to know about sales and special discounts.