How to Get IP Address in React JS?

Sep 22, 2022 . Admin

Hello Folks,

In this tutorial, you will discover react js get ip address. let’s discuss about how to get ip address in react js. In this article, we will implement a how to get user ip address in react js. you will learn how to get client ip address in react.js.

In this example, i will give you very simple example of how to get client ip address in react js app. we will use "https://geolocation-db.com/json/" api using "axios" library to get user ip address in react js.

So, let's see follow the below step to create simple example.

Step 1: Create React JS App

In this step, open your terminal and execute the following command on your terminal to create a new react app:

npx create-react-app react-axios-example
Step 2: Install Axios npm Package

In this step, we need to install axios npm package to use their functions. let's run below command:

npm install axios
Step 3: Update App.js Component

Here, we will call two apis for getting posts and another for deleting post using axios request.

src/App.js
import './App.css';
import { useState, useEffect } from 'react'
import axios from 'axios'

function App() {
  
  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( () => {
    getData()

  }, [])

  return (
    <div className="App">
      <h1>How to Get IP Address in React JS? - MyWebtuts.com</h1>
      <h2>Your IP Address is: </h2>
      <h4>{ip}</h4>
    </div>
  );
}

export default App;
Step 4: Run React JS App

In the last step run your project using bellow command.

npm start
Output

I hope it can help you...

#React JS