How to get a client or user IP address using React JS code example

In this article, we are going to explore how to get a client or user IP address using reactJS. Before this let’s understand what IP address is.

In simpler words, an IP address is a string of integers that uniquely identifies a computer machine. It’s similar to how a house has an address for receiving mail; similarly, your computer has an address for receiving data from the internet. When searching for a global connection, the term protocol refers to a set of rules that must be followed. Exact standards (guidelines) for connecting over the Internet define the networking element of the Internet.

With VPN and Tor, IP may no longer be a reliable source of information. Even so, there are times when we need to record that information. Surprisingly, there isn’t a built-in ReactJS way for displaying the client’s IP address. You may certainly acquire such information using the Axios function or manually.

If you want a user or client IP address then follow these steps: if you have yarn installed on your machine then run the yarn command otherwise npm depends on your choice.

Step1: Create a react project using these commands.

npx create-react-app yourprojectname

#or

yarn create react-app yourprojectname

Step2: Install Axios on your project

npm install axios

#or

yarn add axios

Step3: 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 we’re simply getting the IP address from https://geolocation-db.com/json/ and modifying our IP state to show the current IP address. Using this API, we can also get information about the current user’s country, city, state, latitude, and longitude.

img

You may now use the IP address of the person who is accessing your site to produce a list of people who have visited your site by nation, city, or state. You may also make a list for blacklisting IP addresses and other purposes.

That’s all for this article if you have any confusion contact us through our website or email us at [email protected] or by using LinkedIn

Leave a Comment