How to get user IP address in React JS
I was working on a project and the client asked me for functionality to block some IP addresses. The client will create a list of IP addresses that need to be blocked on the front end. I was a bit confused as React js is a frontend framework and there is no way I can get the IP address of the users using a frontend framework. After some time I found a website which on visiting can give me the user IP address in JSON format. So I thought why not create that functionality using this site. So today I will show you how to get a user's IP address in React JS.
- Create a react project.
npx create-react-app yourprojectname#oryarn create react-app yourprojectname
2. Now install Axios on your project
npm install axios#oryarn add axios
3. Now open your app.js file and remove unnecessary code and paste the below code.
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.
Update 01–04–2023
For some reason the https://geolocation-db.com/json/ API is not working so I have replaced it with a new API https://api.ipify.org/?format=json and the same updated code can be found in codesandbox and GitHub.
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 the Live code and GitHub repository for reference.