Altcademy - a Forbes magazine logo Best Coding Bootcamp 2023

How to get json data from url in ReactJS

Introduction

While learning programming, you might come across a task that involves fetching JSON (JavaScript Object Notation) data from a URL. In this blog post, we will focus on how to accomplish that using ReactJS, a popular JavaScript library for building user interfaces. Don't worry if some of these terms sound like jargons; we'll break them down as we go along.

What is JSON?

JavaScript Object Notation (JSON) is a format for structuring data. It's often used when data is sent from a server to a web page. JSON is essentially a way of representing data that looks like JavaScript objects.

For example, a simple JSON data might look like this:

{
    "name": "John",
    "age": 30,
    "city": "New York"
}

The above JSON represents a person (John) who is 30 years old and lives in New York.

What is ReactJS?

ReactJS, or simply React, is a JavaScript library created by Facebook. It's mainly used for building fast and interactive user interfaces for web applications. It's like the “view” in the MVC (Model-View-Controller) architecture. Think of it as a construction kit of pre-made parts that you can put together to build a web application.

Fetching JSON Data from a URL in ReactJS

To retrieve JSON data from a URL, we will use the Fetch API, a modern, promise-based API for making asynchronous HTTP requests in the browser. "Promise-based" means that it allows us to write asynchronous code in a more synchronous manner.

So, how do we use it? Let's go step by step.

Step 1: Create a New React Component

First, we need a place to display the fetched data. For this purpose, we'll create a new React component. In React, a component is like a building block of your application.

Here is a basic example of a React component:

import React from 'react';

class MyComponent extends React.Component {
    render() {
      return (
        <div>
          Hello, I'm a React component!
        </div>
      );
    }
}
export default MyComponent;

This component, when rendered, will simply display the text "Hello, I'm a React component!"

Step 2: Use the Fetch API to Get Data

Now, let's use the Fetch API to get data from a URL. We'll do this in the componentDidMount lifecycle method. In React, lifecycle methods are special methods that automatically get called as part of the lifecycle of a component. componentDidMount gets called right after the component gets added to the DOM, making it a good place to fetch data.

Here's how you can use the Fetch API:

componentDidMount() {
    fetch('https://api.example.com/items')
        .then(response => response.json())
        .then(data => this.setState({ items: data }));
}

In this code, fetch('https://api.example.com/items') makes a GET request to the URL. The Fetch API returns a promise that resolves to the Response object representing the response to the request. This response object is then converted into JSON format using response.json(). Finally, we update the component's state with the fetched data.

Step 3: Display the Fetched Data

After fetching the data, we need to display it. We can do this in the render method of our component.

render() {
    const { items } = this.state;
    return (
        <div>
            {items.map(item => (
                <div key={item.id}>
                    <h1>{item.title}</h1>
                    <p>{item.body}</p>
                </div>
            ))}
        </div>
    );
}

In this code, we are iterating over the items in our state using the map function and returning a new array of JSX elements. Each item is displayed with its title and body.

Wrapping Up

Fetching JSON data from a URL in ReactJS may sound complicated at first, but once you understand the concepts, it becomes a straightforward task. Remember, practice is the key to mastering a new skill. So, go ahead and try fetching data from different APIs and displaying it in your React application. Happy coding!