How to install and use axios in react js?
April 04, 2023Hi Friends π,
Welcome To aGuideHub!
To install and use axios in React js, you have to use the npm
or yarn
package manager that is how you can install the axios
library into your project.
Today, I am going to show you, how to install and use axios in react js.
Install Axios
Install the following packages to use Axios
in react js.
npm
npm install axios
yarn
yarn add axios
Table of contents
- Create a new React JS project.
- Import Axios into your React component
- Use Axios to make HTTP requests.
Letβs start with the first step.
Step 1: Create a new React JS project.
First you have to install the React project. You should use create-react-app
command to create a new React project.
npx create-react-app my-app
cd my-app
npm start
Step 2: Import Axios into your React component.
After installing Axios, you have to import your React component. To do this, add the following line to the top of your component file.
import axios from "axios";
Step 3: Use Axios to make HTTP requests.
The code you provided is a function named createPost
which uses Axios to make a POST
request to the specified URL
.
function createPost() {
axios
.post(baseURL, {
title: "Hello World!",
body: "This is a new post."
})
.then((response) => {
setPost(response.data);
});
}
ReactJS use axios example.
This code below is an example, When the Create Post
button is clicked the createPost
function is called. This function makes a POST
request to the API
with a title and body for the new post. The result of the POST
request is also stored in the POST
state variable using setPost
.
App.js
import axios from "axios";
import React from "react";
const baseURL = "https://jsonplaceholder.typicode.com/posts";
export default function App() {
const [post, setPost] = React.useState(null);
React.useEffect(() => {
axios.get(`${baseURL}/1`).then((response) => {
setPost(response.data);
});
}, []);
function createPost() {
axios
.post(baseURL, {
title: "Hello World!",
body: "This is a new post."
})
.then((response) => {
setPost(response.data);
});
}
if (!post) return "No post!"
return (
<div>
<h1>{post.title}</h1>
<p>{post.body}</p>
<button onClick={createPost}>Create Post</button>
</div>
);
}
Check the output of the above code example.
Here, we are provided code sandbox links for the above program to install and use axios in React js. Then you can use whenever you went and do the changes as per your requirements.
All the best π