top of page

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
bottom of page