const { useState, useEffect } = React; const width = 960; const height = 500; const margin = { top: 20, right: 30, bottom: 65, left: 220 }; const App = () => { const [data, setData] = useState(null); const [loading, setLoading] = useState(true); const [error, setError] = useState(null); useEffect(() => { const sources = [ 'https://raw.githubusercontent.com/SreejaB-code/Activity6_population.csv-/main/Activity6_Population.csv', 'https://gist.githubusercontent.com/SreejaB-code/370dbc87d96360de9a7074e4e250b3d6/raw/0a1704fcc6e3cd23ea81b6154a143c8ee1ed8326/Activity6_population.csv', ]; const fetchData = async () => { for (const url of sources) { try { const res = await fetch(url); if (!res.ok) continue; const text = await res.text(); const parsed = d3.csvParse(text, (d) => ({ Country: d.Country || d['Country Name'], Population: +d['Population-2020'] || +d['2020'], })); const topCountries = parsed .filter((d) => !isNaN(d.Population)) .sort((a, b) => b.Population - a.Population) .slice(0, 30); setData(topCountries); setLoading(false); return; } catch (err) { console.error(`Failed to load ${url}:`, err); continue; } } setError("Unable to fetch live data. Using default sample."); setData([ { Country: 'China', Population: 1439323776 }, { Country: 'India', Population: 1380004385 }, { Country: 'United States', Population: 331002651 }, { Country: 'Indonesia', Population: 273523615 }, { Country: 'Pakistan', Population: 220892340 }, ]); setLoading(false); }; fetchData(); }, []); if (loading) return
Loading... Check console for logs.
; const innerHeight = height - margin.top - margin.bottom; const innerWidth = width - margin.left - margin.right; if (!data || data.length === 0) { return
Data missing or empty
; } const xScale = d3.scaleLinear() .domain([0, d3.max(data, (d) => d.Population)]) .range([0, innerWidth]) .nice(); const yScale = d3.scaleBand() .domain(data.map((d) => d.Country)) .range([0, innerHeight]) .padding(0.2); return (
{error &&
{error}
} {/* Bottom axis */} {xScale.ticks(5).map((tick) => ( {(tick / 1000000).toFixed(0)}M ))} Population (2020) {/* Left axis */} {yScale.domain().map((country) => ( {country} ))} {/* Bars */} {data.map((d, i) => ( ))}
Total Countries: {data.length}
); }; ReactDOM.render(, document.getElementById('root'));