Getting the IP address of a user in a client-side application like React is not directly possible due to browser security restrictions. If you use a backend API such as Node, Python, or SpringBoot, you can retrieve the client IP address in that back end and send it to the React app as a part of the API response.
However, you can use public APIs that return the user's IP address.
Such public APIs are https://api.ipify.org?format=json
and https://geolocation-db.com/json/
. Make sure they are still operational before using them.
import React, { useEffect, useState } from 'react'
const IPAddress = () => {
const [ipAddress, setIPAddress] = useState('')
useEffect(() => {
fetch('https://api.ipify.org?format=json')
.then(response => response.json())
.then(data => setIPAddress(data.ip))
.catch(error => console.log(error))
}, []);
return (
<div>
<h1>Your IP Address is: {ipAddress}</h1>
</div>
)
}
export default IPAddress;
In this example, the useEffect
hook makes the fetch request when the component mounts, and the useState
hook stores the fetched IP address. The IP address is then displayed in the component.
If you need more information than the client IP address, you can use the geolocation-db
public API endpoint. It provides more information about the client's geolocation. Here is how to achieve that.
import { useEffect, useState } from "react"
export const SignupForm = () => {
const [ipAddress, setIPAddress] = useState('')
const [country, setCountry] = useState('')
const [latitude, setLatitude] = useState('')
const [longitude, setLongitude] = useState('')
useEffect(() => {
fetch('https://geolocation-db.com/json/')
.then(response => response.json())
.then(data => {
setIPAddress(data.IPv4)
setCountry(data.country_name)
setLatitude(data.latitude)
setLongitude(data.longitude)
})
.catch(error => console.log(error))
}, [])
return (
<div>
<p>Your IP Address is: {ipAddress}</p>
<p>Your country is: {country}</p>
<p>Your latitude is: {latitude}</p>
<p>Your longitude is: {longitude}</p>
</div>
)
}
Please note that the above approaches will provide the public IP address the user uses to access the internet. That could be the IP address of a proxy or VPN if the user is using such services. Also, always be mindful and respectful of user privacy concerns when using client-related data.