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
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
If you need more information than the client IP address, you can use the
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.