top of page
Writer's pictureThe Tech Platform

How to get user IP address in React JS



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

2 comments

Recent Posts

See All

2 Comments


Guest
Apr 01

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

Edited
Like

Db IP
Db IP
May 02, 2022

Thanks for sharing the script though this blog about how to get user IP in react js.

Like
bottom of page