Axios in React.js

Musab Abbasi
5 min readNov 22, 2021

--

What is Axios?

Axios is a promise-based HTTP Client for node.js and the browser. It is isomorphic (= it can run in the browser and nodejs with the same codebase). On the server-side it uses the native node.js http module, while on the client (browser) it uses XMLHttpRequests.

Features

  • Make XMLHttpRequests from the browser
  • Make http requests from node.js
  • Supports the Promise API
  • Intercept request and response
  • Transform request and response data
  • Cancel requests
  • Automatic transforms for JSON data
  • Client side support for protecting against XSRF

Creating React.js App

We will be using Axios with React.js and make http requests. To create a React application we will be executing the below command.

npx create-react-app

I am naming my react app as frontend for the sake of simplicity.

Once your react.js app is created go to your terminal and install axios by the below command

npm install axios

Lets create a folder in src named as components. We will be creating all new components in it (if any) and importing it in App.js.

Creating a Form component

Next we will be creating a component called as Form.jsx where we will be creating our form, then handling the fields with useStates and Posting it to a backend server.

Now write below code in your Form.jsx file

import React from "react";
function form(){
return(
<div className="form"></div>
);
}
export default form;

Now lets create a form in it and import it in App.js file.

import Form from "./components/Form";
function App() {
return (
<div className="">
<Form />
</div>
);
} export default App;

Form.jsx

import React from "react";
function form(){
return(
<div className="form">
<h2>User Form</h2>
<form>
<label htmlFor="">Username</label>
<br />
<input type="text" placeholder="Enter your username" />
<br />
<label htmlFor="">Email Address</label>
<br />
<input type="email" placeholder="Enter your Email Address" />
<br />
<label htmlFor="">Password</label>
<br />
<input type="password" placeholder="Enter your Password" />
<br />
<button type="submit">Submit</button>
</form>
</div>
);
} export default form;

Now if you click on submit button you will observe that the page reloads itself. We don’t want this behaviors, instead we will prevent the default behavior of this form.

import React from "react"; 
function form(){
function submitForm(e){
e.preventDefault()
}
return(
<div className="form">
<h2>User Form</h2>
<form onSubmit={submitForm}>
<label htmlFor="">Username</label>
<br />
<input type="text" placeholder="Enter your username" />
<br />
<label htmlFor="">Email Address</label>
<br />
<input type="email" placeholder="Enter your Email Address" />
<br />
<label htmlFor="">Password</label>
<br />
<input type="password" placeholder="Enter your Password" />
<br />
<button type="submit">Submit</button>
</form>
</div>
);
}
export default form;

We have added a different function in Form tag and handled that function by added e.defaultPrevent() function.

Now since our we have prevented the default behavior of our form, lets now create state for each element.

import React, { useState } from "react"; 
function Form(){
var [username, setUsername] = useState("");
var [email, setEmail] = useState("");
var [password, setPassword] = useState("");
function submitForm(e){
e.preventDefault()
}
return(
<div className="form">
<h2>User Form</h2>
<form onSubmit={submitForm}>
<label htmlFor="">Username {username}</label>
<br />
<input type="text" placeholder="Enter your username" onChange={(e)=>{setUsername(e.target.value)}} /> <br />
<label htmlFor="">Email Address {email}</label>
<br />
<input type="email" placeholder="Enter your Email Address" onChange={(e)=>{setEmail(e.target.value)}} /> <br />
<label htmlFor="">Password {password}</label>
<br />
<input type="password" placeholder="Enter your Password" onChange={(e)=>{setPassword(e.target.value)}} /> <br />
<button type="submit">Submit</button>
</form>
</div>
);
}
export default Form;

Here we have created states and setting them onChange of their values.

import React, { useState } from "react";
function Form(){
var [username, setUsername] = useState("");
var [email, setEmail] = useState("");
var [password, setPassword] = useState("");
function submitForm(e){
e.preventDefault();
const re = /^(([^<>()[\]\\.,;:\s@"]+(\.[^<>()[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
if(username!=="" || email!=="" || password!==""){
if(re.test(String(email).toLowerCase())){
} else{
alert("Please enter a valid Email Address")
} } else{
alert("Please Enter all fields")
}
}
return(
<div className="form">
<h2>User Form</h2>
<form onSubmit={submitForm}>
<label htmlFor="">Username {username}</label>
<br />
<input type="text" placeholder="Enter your username" onChange={(e)=>{setUsername(e.target.value)}} /> <br />
<label htmlFor="">Email Address {email}</label>
<br />
<input type="email" placeholder="Enter your Email Address" onChange={(e)=>{setEmail(e.target.value)}} /> <br />
<label htmlFor="">Password {password}</label>
<br />
<input type="password" placeholder="Enter your Password" onChange={(e)=>{setPassword(e.target.value)}} /> <br />
<button type="submit">Submit</button>
</form>
</div>
);
}
export default Form;

Now we have applied some validation on our form so that our data will be ready to be posted.

Using Axios for Posting data

Now we will be importing Axios since we have installed it earlier in this article.

We will be sending a POST request and sending our data including username, email address and password of the user that was enter using the form.

import React, { useState } from "react";const axios = require('axios');function Form(){var [username, setUsername] = useState("");var [email, setEmail] = useState("");var [password, setPassword] = useState("");function submitForm(e){e.preventDefault();const re = /^(([^<>()[\]\\.,;:\s@"]+(\.[^<>()[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;if(username!=="" || email!=="" || password!==""){if(re.test(String(email).toLowerCase())){axios.post('/user', {username: username,email: email,password: password}).then(function (response) {console.log(response);}).catch(function (error) {console.log(error);});}else{alert("Please enter a valid Email Address")}}else{alert("Please Enter all fields")}}return(<div className="form"><h2>User Form</h2><form onSubmit={submitForm}><label htmlFor="">Username {username}</label><br /><input type="text" placeholder="Enter your username" onChange={(e)=>{setUsername(e.target.value)}} /><br /><label htmlFor="">Email Address {email}</label><br /><input type="email" placeholder="Enter your Email Address" onChange={(e)=>{setEmail(e.target.value)}} /><br /><label htmlFor="">Password {password}</label><br /><input type="password" placeholder="Enter your Password" onChange={(e)=>{setPassword(e.target.value)}} /><br /><button type="submit">Submit</button></form></div>);}export default Form;

Now if you have a backend you might get a CORS error you need to handle it in your back. Once everything is working you should be getting a response back after posting data using Axios.

I will be posting Node.js(Backend) tutorial also and will be showing how you can handle the post request on backend as well.

If you think this article was helpful please subscribe to my newsletter because I will be posting multiple tutorials, tricks and technique regarding React.js, Node and other helpful web development languages and tool.

--

--

Musab Abbasi

Computer Science Graduate with MERN stack website development expertise.