React is a popular JavaScript library for building user interfaces, and one of the most common use cases is fetching data from an API. In this blog post, we will explore how to fetch JSON data in a React app and display it in a component.
The first step is to install the axios
library, which is a popular library for making HTTP requests in JavaScript. You can install it by running the following command in your project's root directory:
npm install axios
Once axios
is installed, we can import it in our component and use it to fetch JSON data. One way to do this is by using the componentDidMount()
lifecycle method, which is called immediately after a component is rendered. Inside this method, we can make a call to the API and update the component's state with the data we receive. Here's an example of how this can be done:
import React, { Component } from 'react';
import axios from 'axios';
class MyComponent extends Component {
constructor(props) {
super(props);
this.state = {
data: []
};
}
componentDidMount() {
axios.get('https://example.com/data.json')
.then(response => {
this.setState({ data: response.data });
})
.catch(error => {
console.log(error);
});
}
render() {
return (
<div>
{this.state.data.map(item => (
<div key={item.id}>
<h2>{item.title}</h2>
<p>{item.description}</p>
</div>
))}
</div>
);
}
}
export default MyComponent;
In this example, we are using axios.get()
to fetch the data from the API, and passing in the URL of the JSON file. The .then()
method is called when the data is successfully returned, and it sets the component's state with the data we received. We can then map through the data in the render method and display it in our component.
It's important to note that this code will only work if the API you are calling allows CORS (Cross-Origin Resource Sharing) otherwise it will fail.
It's also worth mentioning that, as an alternative to componentDidMount()
, you can use the useEffect
hook from React to fetch the data and update the component's state. This allows for a more modern and efficient way of fetching and handling data in functional components.