JSON HTML React feat

Display Json Data in HTML Using React (Simple Tutorial)

In Tutorial by Rune

JSON data in html with react

In this tutorial, I’m going to show you how to display json files from local storage and external API using JavaScript and the React JS framework.

If you are interested in using vanilla JavaScript to display json data in HTML, then check out this post.

Open the terminal and update react version. You should update the react version with this command:

npm install create-react-app@latest

In order to be able to run the command above, you need to have Node.js installed. You can do that by going to the Node.js website.

Now let us create our React app.

1. Creating the react app

Create a new project with the npm command. Open a command window and write the following line:

npx create-react-app json-manipulation

It will create the folder of the project. After installation, write this command
in the cmd window to go to the folder:

cd json-manipulation

If there is any confusion of folder path, then take a look at the final project structure image at the end of this article.

2. Handling basic files

Open App.js file in your editor and handle its content for our app. This file is in the src folder.

Firstly, Remove the code that existed within the project and create an App.js file with the following code:

import React, { Component } from 'react';
import logo from './logo.svg';
import './App.css';

class App extends Component {
  render() {
    return (
      <div className="App">
        
      </div>
    );
  }
}

export default App;

That class is for the App component.

Next, Create a new folder called components in src folder. The path is src/components. This folder contains React components including Javascript and CSS files. We will be fetching an external API first and then create local json handling

3. Fetching an API

We will use a fake API from jsonplaceholder.com website. This is an example of returned data from that website with the following URL

https://jsonplaceholder.typicode.com/posts

[
    {
      "userId": 1,
      "id": 1,
      "title": "sunt aut facere repellat provident occaecati excepturi optio reprehenderit",
      "body": "quia et suscipit\nsuscipit recusandae consequuntur expedita et cum\nreprehenderit molestiae ut ut quas totam\nnostrum rerum est autem sunt rem eveniet architecto"
    },
    {
      "userId": 1,
      "id": 2,
      "title": "qui est esse",
      "body": "est rerum tempore vitae\nsequi sint nihil reprehenderit dolor beatae ea dolores neque\nfugiat blanditiis voluptate porro vel nihil molestiae ut reiciendis\nqui aperiam non debitis possimus qui neque nisi nulla"
    }
]

Handling json files from a website is called: “consuming a RESTful API”.

3.1 Adding a component

Firstly, add a new folder called OnlinePosts. This folder has a path src/components/OnlinePosts/. It contains files for handling online json. Then, create a new file called GetOnlinePosts.js with path src/components/OnlinePosts/GetOnlinePosts.js. It contains the component that fetches the json file and puts it in an HTML file with styles.

Next, add this line to import React component from packages.

import React, { Component } from 'react';

Next, create the class that inherits from the Component class. This class have a constructor that contains props as a parameter and the state of that component. This state has three properties error to check if there is an error in connection, isLoaded to check if the fetching process is finished and posts that contains the json content.

class GetOnlinePosts extends Component {
    constructor(props){
        super(props);
        this.state = {
            error : null,
            isLoaded : false,
            posts : []        
        };
    }
  }

3.2 Fetching the json

Firstly, we add a componentDidMount() function which has the fetching procedure. It’s a function in the React component class itself. It’s called immediately after the component is mounted.

This is the code in this function.

componentDidMount() {
        // I will use fake api from jsonplaceholder website
        // this return 100 posts 
        fetch("https://jsonplaceholder.typicode.com/posts")
        .then( response => response.json())
        .then(
            // handle the result
            (result) => {
                this.setState({
                    isLoaded : true,
                    posts : result
                });
            },

            // Handle error 
            (error) => {
                this.setState({
                    isLoaded: true,
                    error
                })
            },
        )
    }

https://jsonplaceholder.typicode.com/posts is the URL for the API.

We make the first then statement to get the response. The json() functions returns a promise, so we need another thento check the result.

When the response is successful we add result to posts variables and change isLoaded to true and sets state of the component by using setState({}) method.

If there is an error, we will change error from null to assign its value.

3.3 Handling the output in html

We should handle the output in render() function

    render() {
        const {error, isLoaded, posts} = this.state;

        if(error){
            return <div>Error in loading</div>
        }else if (!isLoaded) {
            return <div>Loading ...</div>
        }else{
            return(
                <div>
                    <ol>
                    {
                        posts.map(post => (
                            <li key={post.id} align="start">
                                <div>
                                    <p>{post.title}</p>
                                    <p>{post.body}</p>
                                </div>
                            </li>
                        ))
                    }
                    </ol>
                </div>
            );
        }    
    }

We assign the state values to variables. The reason for this is so we can refer to variables as posts, instead of this.state.posts.

Then, we check the result. If we have an error, we will display that an error occured in the div tag. If it’s loading return a div with the text Loading ....

If there are no errors, it will return a div with an ordered list. We use the map() function to return each element as item in the ordered list. The li tag has a key and its content. The content consists of two paragraph, tag one for title and the other for the body of the post.

3.4 Adding styles

We add CSS styles by creating a new file in OnlinePosts called GetOnlinePosts.css with styles for item, title and body. We add the title class with font size 18pt and color blueviolet. We add an item class with margin 10px, color crimson and font size 20pt. The last class is body of the post with a font size 16pt and color black.

.title{
    font-size: 18pt;
    color: blueviolet;
}

.item{
    margin: 10px;
    font-size: 20pt;
    color: crimson;
}

.body{
    font-size: 16pt;
    color: black;
}

Now, we are adding className in GetOnlinePosts.js and changing the ordered list

<ol className="item">
{
posts.map(post => (
    <li key={post.id} align="start">
                  <div>
                      <p className="title">{post.title}</p>
                      <p className="body">{post.body}</p>
                  </div>
          </li>
      ))
      }
</ol>

You should import css files in the top of the file.

import './GetOnlinePosts.css';

3.5 The final file GetOnlinePosts.js

import React, { Component } from 'react';
import './GetOnlinePosts.css'
// get posts from online api
// it's return a json file
class GetOnlinePosts extends Component {
    constructor(props){
        super(props);
        this.state = {
            error : null,
            isLoaded : false,
            posts : []          
        };
    }

    componentDidMount(){
        // I will use fake api from jsonplaceholder website
        // this return 100 posts 
        fetch("https://jsonplaceholder.typicode.com/posts")
        .then( response => response.json())
        .then(
            // handle the result
            (result) => {
                this.setState({
                    isLoaded : true,
                    posts : result
                });
            },

            // Handle error 
            (error) => {
                this.setState({
                    isLoaded: true,
                    error
                })
            },
        )
    }

    render() {
        const {error, isLoaded, posts} = this.state;

        if(error){
            return <div>Error in loading</div>
        }else if (!isLoaded) {
            return <div>Loading ...</div>
        }else{
            return(
                <div>
                    <ol className="item">
                    {
                        posts.map(post => (
                            <li key={post.id} align="start">
                                <div>
                                    <p className="title">{post.title}</p>
                                    <p className="body">{post.body}</p>
                                </div>
                            </li>
                        ))
                    }
                    </ol>
                </div>
            );
        }
      
    }
  }
  
  export default GetOnlinePosts;

4. Displaying the local json

Let’s start with handle json from local storage (offline). Firstly, add a new folder in the components folder called LocalPosts. This folder has a file called posts.js.

const posts = [
    {
        "id" : 1,
        "title" : "Football",
        "body" : "There are some great matches and good"
    },
    {
        "id" : 2,
        "title" : "Volleyball",
        "body" : "There are some great matches"
    },
    {
        "id" : 3,
        "title" : "Baseball",
        "body" : "It's a bad hobby"
    }
];

export default posts;

4.1 Fetching and displaying local json

Then, add a javascript file called GetLocalPosts.js. This javascript file has a component to deal with local object from the file posts.js. This is simpler than fetching data from an external API. You should import posts.js in GetLocalPosts.js

import React, { Component } from 'react';

import posts from './posts.js';
// get posts from online api
// it's return a json file
class GetLocalPosts extends Component {
    constructor(props){
        super(props);
        this.state = {            
            posts :posts            
        };
    }

    render() {
        const {posts} = this.state;
        return(
            <div>
                <ol className="item">
                {
                    posts.map(post => (
                        <li key={post.id} align="start">
                            <div>
                                <p className="title">{post.title}</p>
                                <p className="body">{post.body}</p>
                            </div>
                        </li>
                    ))
                }
                </ol>
            </div>
        );
    }
  }
  
  export default GetLocalPosts;

5. Adding components to App.js

You should add two components GetLocalJson.js and GetOnlineJson.js to App.js

import React, { Component } from 'react';
import GetOnlinePosts from './components/OnlinePosts/GetOnlinePosts';
import logo from './logo.svg';
import './App.css';
import GetLocalPosts from './components/LocalPosts/GetLocalPosts';

class App extends Component {
  render() {
    return (
      <div className="App">
        <h1 className="header">Local Storage</h1>
        <GetLocalPosts/>
        <br/>
        <h1 className="header">External API</h1>
        <GetOnlinePosts/>
      </div>
    );
  }
}

export default App;

In the h1 tag, we have a className called header. Add this class in the App.css file at the end of the file like in the following code. Don’t remove any other classes.

.header{
  color: crimson;
}

Here you can see the final project structure:

6. Running the program

Go back to the cmd window and write this command:

npm start

This will open the default browser in localhost.