Skip to content

Contact sales

By filling out this form and clicking submit, you acknowledge our privacy policy.

How to Use React.js and Complex JSON Objects

Jul 31, 2020 • 8 Minute Read

Introduction

One of the key tasks of a frontend developer is integrating backend APIs into apps. Modern APIs widely follow the RESTful architecture where an endpoint receives a request from the client and sends back a response irrespective of the client. GET APIs or endpoints that are used only to retrieve data from a server using a popular data format called JSON (JavaScript Object Notation). They often send back a complex JSON object with deeply nested objects and arrays.

This guide aims to explain how you can retrieve relevant information from a complex JSON object in your React app and store that data in the state, or pass it down as props when required.

App Overview and Setup

The example in this guide will build a small React app that consumes the endpoint https://reqres.in/api/unknown by breaking down a complex JSON object into simple objects and arrays. The entire data set is fetched and stored by a parent component and then broken down into two separate objects. One object is passed as props to a child component that shows the information contained in that object to the user.

Create a blank react project by running :

      npx create-react-app react-complex-json-app
    

Install Axios, a third party library that goes well with React for making HTTP calls.

      npm install axios
    

Creating Components Boilerplate

Create two simple components to get started. First, the Colors component :

      import React from 'react';

const Colors=()=>{
    return(
        <>
            <h1>This is Colors component</h1>
        </>
    )
}
export default Colors;
    

Now create the Home component and render the Colors component inside it as demonstrated below .

      import React from 'react';
import Colors from './Colors';

const Home=()=>{
    return(
        <>
            <h1>This is home component</h1>
            <Colors/>
        </>
    )
}

export default Home;
    

Finally, render the Home component inside App.js .

      import React from 'react';
import './App.css';
import Home from './Components/Home';

function App() {
  return (
    <div className="App">
      <h2>React JSON</h2>
      <Home/>
    </div>
  );
}

export default App;
    

Requesting a Complex JSON

Consider the following code for making a GET request to a REST API.

      import React,{useEffect,useState} from 'react';
import Colors from './Colors';
import axios from 'axios';

const Home=()=>{
    useEffect(()=>{
        axios.get('https://reqres.in/api/unknown')
            .then(res=>{
                console.log(res)
            })
            .catch(err=>{
                console.log(err);
            })
    },[])
    return(
        <>
            <h1>{Data.Company}</h1>
            <p>{Data.Description}</p>
            <Colors/>
        </>
    )
}

export default Home;
    

Analyzing Complex JSON Object

The JSON response as it is contains a lot of unnecessary information (such as config, headers, etc.), and returns all relevant information inside a data object. This data object contains the actual data that the user might be interested in. A good and simple practice to analyze and break down complex JSON responses is using console statements to see the properties attached to an object as demonstrated below.

      useEffect(()=>{
        axios.get('https://reqres.in/api/unknown')
            .then(res=>{
                console.log('Response from main API: ',res)
                console.log('Home Data: ',res.data.ad)          
                console.log('Colors Data: ',res.data.data)
            })
            .catch(err=>{
                console.log(err);
            })
    },[])
    

The data object contains two relevant objects attached as properties: data and ad. The ad object is supposed to be consumed by the Home component for displaying the name of the company and its motto.

      company: "StatusCode Weekly"
text: "A weekly newsletter focusing on software development, infrastructure, the server, performance, and the stack end of things."
url: "http://statuscode.org/"
    

The data object is an array of objects where each object contains details about a particular color.

      0: {id: 1, name: "cerulean", year: 2000, color: "#98B2D1", pantone_value: "15-4020"}
1: {id: 2, name: "fuchsia rose", year: 2001, color: "#C74375", pantone_value: "17-2031"}
2: {id: 3, name: "true red", year: 2002, color: "#BF1932", pantone_value: "19-1664"}
3: {id: 4, name: "aqua sky", year: 2003, color: "#7BC4C4", pantone_value: "14-4811"}
4: {id: 5, name: "tigerlily", year: 2004, color: "#E2583E", pantone_value: "17-1456"}
5: {id: 6, name: "blue turquoise", year: 2005, color: "#53B0AE", pantone_value: "15-5217"}
    

Consuming Data from a Complex JSON Response

First, create some state variables to store the entire data. The state variable Data stores details that have to be shown on the Home component, and colorsData stores the details that have to be shown on the Colors component

      const [Data,setData]=useState({
    Company:'',
    Description:''
})
const [colorsData,setColorsData]=useState([])
    

Populate these variables with data inside the .then() method of the API call.

      useEffect(()=>{
    axios.get('https://reqres.in/api/unknown')
        .then(res=>{

            let companyData=res.data.ad;

            setData({Company:companyData.company,Description:companyData.text})
            setColorsData(res.data.data)
        })
        .catch(err=>{
            console.log(err);
        })
},[])
    

Output data from companyData inside the Home component:

      return(
    <>
        <h1>{Data.Company}</h1>
        <p>{Data.Description}</p>
        <Colors data={colorsData}/>
    </>
    

Final Code

Let's now wrap up the guide, with complete code as discussed above.

Home Component

The final code for the Home component is demonstrated below.

      import React,{useEffect,useState} from 'react';
import Colors from './Colors';
import axios from 'axios';

const Home=()=>{
    const [Data,setData]=useState({
        Company:'',
        Description:''
    })
    const [colorsData,setColorsData]=useState([])
    useEffect(()=>{
        axios.get('https://reqres.in/api/unknown')
            .then(res=>{
                console.log('Response from main API: ',res)
                console.log('Home Data: ',res.data.ad)
                let companyData=res.data.ad;
                setData({Company:companyData.company,Description:companyData.text})
                console.log('Colors Data: ',res.data.data)
                setColorsData(res.data.data)
            })
            .catch(err=>{
                console.log(err);
            })
    },[])
    return(
        <>
            <h1>{Data.Company}</h1>
            <p>{Data.Description}</p>
            <Colors data={colorsData}/>
        </>
    )
}

export default Home;
    

Colors Component

Finally, using a component loop, output the information about colors inside the Colors component.

      import React from 'react';

const Colors=({data})=>{
    return(
        <>
          {
            data && data.map((d)=>{
               return(
                    <div className="card" key={d.id} style={{background:d.color}}>
                    <div className="container">
                        <h4><b>{d.name}</b></h4> 
                        <p>{d.color}</p> 
                    </div>
                    </div>
               )
           })
          }
        </>
    )
}

export default Colors;
    

Conclusion

Dealing with complex JSON responses is a necessity today to React developers. It can be tedious at times but isn't a difficult task altogether if done wisely by breaking down large pieces of data into smaller chunks. This can be done by properly observing how an endpoint is giving back data to the frontend, especially the name of the keys, the type of values returned, etc. Working with complex JSON responses also improves your debugging skills.