Visualizing Global User Distribution on Your React Website with Google Analytics Data

Ali Zahid Raja
5 min readNov 3, 2023

--

Global User Distribution for Islam&AI

In this article I will show you how to show your Global User Distribution data from your Google Analytics on your React Website’s Landing Page!

Welcome to the digital age where user interaction on your website can be a treasure trove of insights! If you’re running a website, especially one like “Islam&AI” that caters to a global audience, it’s crucial to understand where your users are coming from. It not only helps in tailoring your content but also in strategizing your marketing efforts. In this comprehensive guide, we’ll explore how to extract user distribution data from Google Analytics and elegantly display it on a map on your React website’s landing page. So, if you’re curious about tracking user activity, displaying data in React using a map, or integrating Google Analytics with React, you’re in the right place. Let’s dive in!

Step 1: Harvesting Data from Google Analytics

The first step is to gather your user distribution data. Here’s how you can download this data from Google Analytics:

  • Log in to your Google Analytics account at analytics.google.com.
  • Navigate to the User section and select User Attributes > Demographic.
  • Here, you’ll see a geographical breakdown of your users’ data.
  • Export this data in your preferred format and import it into a Google Sheet for easy access and manipulation.

Step 2: Enabling Google Sheets API

To access the data programmatically, you need to enable the Google Sheets API:

  • Visit console.google.com and create a new project.
  • In the API & Services dashboard, enable the Google Sheets API.
  • Generate the credentials (API key and OAuth client ID) that you’ll use to authenticate requests from your React application.

Step 3: Integrating Google Sheets with React

With the Google Sheets API enabled and your credentials in hand, it’s time to fetch the data within your React app:

  • Install the use-google-sheets package, which provides a custom hook to read from a Google Sheet.
  • Use the API keys from the previous step to set up the hook and retrieve your user distribution data.
  • The hook will return the data in a JSON format that you can easily manipulate within your application.

Step 4: Mapping the Data with react-simple-maps

To visualize the data, we’ll use react-simple-maps, a library that simplifies the creation of SVG maps in React:

  • Install react-simple-maps along with its dependencies.
  • Import ComposableMap and Geographies components to create a scalable world map.
  • Use the Geography component to render each country and pass the user distribution data as a prop to color the countries based on user count.
  • Utilize a color scale to differentiate between countries with varying user densities.

Step 5: Bringing It All Together on Your Landing Page

With all the pieces in place, integrate the map into your landing page:

  • Ensure the map is responsive and fits neatly within your page design.
  • Add interactivity to the map, like tooltips, to display user data on hover.
  • Optimize performance by memoizing computations and avoiding unnecessary re-renders.

Conclusion

By following these steps, you’ve now successfully integrated a dynamic, data-driven map into your React website, showcasing the global distribution of your users. It’s not only an impressive visual addition to your site but a powerful tool for data-driven decision-making. With this setup, you can continually update and display the latest user trends directly from Google Analytics, keeping your finger on the pulse of your audience’s geography.

FAQs:

How do I track user activity on my React website?

Use Google Analytics with react-ga or gtag.js for tracking user interactions.

What’s the best map API for React?

react-simple-maps for SVG maps and react-google-maps for Google Maps integration are popular choices.

How do I get data from Google Analytics into my React app?

Use the Google Sheets API to fetch data exported from Google Analytics.

Does Google Analytics work with React applications?

Yes, you can integrate Google Analytics with React using various libraries like react-ga.

How do I render a map in React?

Utilize libraries like react-simple-maps for SVG maps or react-google-maps for Google Maps.

By following these guided steps and leveraging the powerful combination of Google Analytics, Google Sheets API, and react-simple-maps, you'll have a visually stunning and informative map that enhances your website's user experience and provides valuable insights into your audience. Happy coding!

Oh, and I almost forgot, the code files!!!

MapChart.js

import React from "react";
import {
ComposableMap,
Geographies,
Geography,
Sphere,
Graticule,
} from "react-simple-maps";
import { scaleLinear } from "d3-scale";

const { getCode } = require("country-list");
// URL to a suitable geoJSON. This is a link to a simple world map provided by "react-simple-maps".
const geoUrl = "https://cdn.jsdelivr.net/npm/world-atlas@2/countries-110m.json";

const MapChart = ({ mapData }) => {
// A simple function to scale the number of users to a color
const colorScale = scaleLinear()
.domain([0, 5000])
.range(["#BBFDCD", "#014013"]);

const borderStyle = {
default: {
stroke: "#000", // Black color for the borders
strokeWidth: 0.1,
outline: "none",
},
hover: {
stroke: "#000",
strokeWidth: 0.1,
outline: "none",
},
pressed: {
stroke: "#000",
strokeWidth: 0.1,
outline: "none",
},
};

return (
<div
style={{
width: "100%",
height: "auto",
maxHeight: "100vh",
overflow: "hidden",
}}
>
<h2 style={{ textAlign: "center", marginBottom: "1rem" }}>
Global User Distribution
</h2>
<ComposableMap
projectionConfig={{ scale: 160 }}
style={{
width: "100%",
height: "80vh", // 80% of the viewport height
maxHeight: "100vh",
overflow: "hidden",
}}
>
<Sphere stroke="#000" strokeWidth={0.5} />
<Graticule stroke="#0B95FA" strokeWidth={0.5} />
<Geographies geography={geoUrl}>
{({ geographies }) =>
geographies.map((geo) => {
const d = mapData[getCode(geo.properties.name)];
return (
<Geography
key={geo.rsmKey}
geography={geo}
fill={colorScale(d) || "#DDD"}
style={borderStyle}
/>
);
})
}
</Geographies>
</ComposableMap>
</div>
);
};

export default MapChart;

GlobalMap.js

import React from "react";
import MapChart from "./MapChart";
import useGoogleSheets from "use-google-sheets";

const { getCode } = require("country-list");

const GlobalMap = () => {
const { data, loading, error } = useGoogleSheets({
apiKey: process.env.REACT_APP_GOOGLE_API_KEY,
sheetId: process.env.REACT_APP_GOOGLE_SHEETS_ID,
sheetsNames: ["Sheet1"],
});

if (loading) {
return <div>Loading...</div>;
}

if (error) {
return <div>Error: {error}</div>;
}

const createMapData = (dataArray) => {
return dataArray.reduce((acc, item) => {
const code = getCode(item.Country);
if (code) {
acc[code] = parseInt(item.Users, 10); // Make sure to convert the user count to a number
}
return acc;
}, {});
};

return (
<div>
<MapChart mapData={createMapData(data[0].data)} />
</div>
);
};

export default GlobalMap;

App.js

<GlobalMap />

--

--

Ali Zahid Raja

Founder | CTO | AI, Data & ML Engineer | Creator | Developer | Entrepreneur | Mentor