1. Create a react project.
npx create-react-app yourprojectname
#o
ryarn create react-app yourprojectname
2. Now install Axios on your project
npm install axios
#o
ryarn add axios
3. Now open your app.js file and remove unnecessary code and paste the below code.
import'./App.css';
import {useState,useEffect} from 'react'
import axios from 'axios'
function App(){
//creating IP state
const [ip,setIP] = useState('');
//creating function to load ip address from the API
const getData = async()=>{
const res = await axios.get('https://geolocation-
db.com/json/')
console.log(res.data);
setIP(res.data.IPv4)
}
useEffect(()=>{
//passing getData method to the lifecycle method
getData()
},[])
return(
<div className = "App">
<h2>Your IP Address is</h2>
<h4>{ip}</h4>
</div>
);
}
export default App;
So here we are just fetching the IP address from https://geolocation-db.com/json/ and then changing our IP state to display the current IP address. Through this API we can also fetch the current user country, city, state, latitude, longitude, etc.
Now you have the IP address of the user visiting your site you can use this to create a list of users visiting your site by country, city, or state. You can also create a list for blacklisting the IP and many other things.
Below I Have shared Live code and GitHub repository for reference.
Source: Medium - Manish Mandal
The Tech Platform
Hi, I am trying to get the Ip address and I used the getData function in project. I am getting an error : Access to XMLHttpRequest at 'https://geolocation-db.com/json/' from origin 'http://localhost:3000' has been blocked by CORS policy: Request header field longitude is not allowed by Access-Control-Allow-Headers in preflight response.
I am using this on Next.Js app on frontend
Thanks for sharing the script though this blog about how to get user IP in react js.