React JS Tutorial - Using Axios
In this tutorial, we will learn about using Axios in React. Axios is a lightweight HTTP client based on the XMLHttpRequests service, similar to the Fetch API. It is used to perform HTTP requests in a simple and efficient way.
Installing Axios
To use Axios in our React application, we first need to install it. Switch to the command prompt and run the following command:
npm install axios
Once the installation is complete, Axios is ready to use in our React application.
Running the React Application
Next, run the React application again by typing the following command:
npm start
Creating a New Component
Now, switch to the project and create a new component, for example, "Blog.js". Inside the Blog component, create a class as follows:
import React, { Component } from 'react';
import axios from 'axios';
class Blog extends Component {
state = {
posts:[]
}
componentDidMount(){
axios.get('https://jsonplaceholder.typicode.com/posts')
.then(res=>{
this.setState({
posts:res.data.slice(0,10)
});
});
}
render() {
const {posts} = this.state;
const postList = posts.length?(
posts.map(post=>{
return(
<div key={post.id}>
<h4>{post.title}</h4>
<p>{post.body}</p>
</div>
)
})
):(<div>No post yet</div>);
return (
<div>
<h3>Blog Posts</h3>
{postList}
</div>
)
}
}
export default Blog;
Importing the Blog Component
Go to the App.js file and import the Blog component:
import Blog from './components/Blog';
Adding the Blog Component to the Switch
Now, add the Blog component inside the Switch:
<BrowserRouter>
<Switch>
<Route exact path='/blog' component={Blog}/>
</Switch>
</BrowserRouter>
Testing the Application
Save the changes and let's check the application. Switch to the browser and go to the URL "/blog". You should see the posts displayed on the page.
In this way, you can use Axios in your React application to perform HTTP requests and fetch data from APIs.