- read

Leveraging CoinGecko API for Cryptocurrency Analysis: Crypto Dashboard With React

NinjaCoder 45

Leveraging CoinGecko API for Cryptocurrency Analysis: Crypto Dashboard With React

NinjaCoder
Level Up Coding
Published in
7 min read2 days ago

--

Create a Crypto dashboard using React, Material UI, Chart.js, and the CoinGecko API

In the rapidly evolving world of cryptocurrencies, having access to accurate, up-to-date information is crucial. That’s where the Crypto Dashboard comes in. This tool, which I’ve developed and hosted on GitHub, leverages the CoinGecko API to provide real-time data on various cryptocurrencies.

The CoinGecko API

CoinGecko’s API is a robust tool for anyone interested in cryptocurrency. It provides access to a wealth of information, including current prices, historical data, and more. For those who subscribe to CoinGecko’s premium plan, there are even more features available, including exclusive endpoints.

To use the Crypto Dashboard, you’ll need to obtain an API key from CoinGecko. This can be done by visiting the CoinGecko API documentation and following the instructions there.

If you’re interested in accessing the exclusive endpoints available to premium subscribers, you can find more information in the CoinGecko Pro API Guide.

As a bonus, you can use my referral code CGNINJACODERX when signing up for CoinGecko’s premium plan to receive a $500 discount.

Configuring the Crypto Dashboard

Once you have your API key, you’ll need to configure the Crypto Dashboard. This involves replacing 'YOUR_API_KEY' with your actual API key in the configuration file of the Crypto Dashboard repository. I have build this complete repository here

Inside the Crypto Dashboard Repository

The Crypto Dashboard repository contains several files that work together to fetch and display cryptocurrency data. Here’s a brief overview:

/my-app
├── README.md
├── node_modules
├── package.json
├── public
│ ├── index.html
│ ├── favicon.ico
│ └── manifest.json
└── src
├── components
│ ├── Dashboard.js
│ └── // other component files...
├── App.js
├── App.css
├── index.js
└── index.css
  • README.md: This is the file where you can put instructions or documentation for your project.
  • node_modules: This directory is where all the modules of code that your project depends on (npm packages) are automatically installed.
  • package.json: This is the file that has metadata relevant to the project. This file is used to give information to npm that allows it to identify the project as well as handle the project’s dependencies.
  • public/index.html: This is the HTML file that serves as the entry point for your web page.
  • src: This directory is where you put all of your source code for your React application.
  • components: This directory is where you put all of your React components. In this case, it includes Dashboard.js.
  • App.js: This is the main React component file.
  • index.js: This is the JavaScript entry point file.

Please note that this is a simplified structure and a real-world application might have more files and directories (e.g., for tests, other assets, and complex state management). You might need to modify it according to your needs.

Dashboard.js

This dahsboard uses the free api’s provided by CoinGecko and does not require an api key to signup

import React, { useEffect, useState } from 'react';
import { makeStyles } from '@material-ui/core/styles';
import { Line } from 'react-chartjs-2';
import axios from 'axios';
const useStyles = makeStyles((theme) => ({
root: {
flexGrow: 1,
},
}));
export default function Dashboard() {
const classes = useStyles();
const [data, setData] = useState({});
useEffect(() => {
const fetchData = async () => {
try {
const result1 = await axios.get('https://api.coingecko.com/api/v3/ping');
const result2 = await axios.get('https://api.coingecko.com/api/v3/simple/price?ids=bitcoin&vs_currencies=usd');
..........
setData({
ping: result1.data,
simplePrice: result2.data,
.......
});
} catch (error) {
console.error("Error fetching data", error);
}
};
fetchData();
}, []);
return (
<div className={classes.root}>
{/* Render your charts and other components here using the fetched data */}
</div>
);
}

In this code simplePrice contains the price data for Bitcoin. You’ll need to adjust this according to how your state is structured and how you’re storing your fetched data. Also, make sure that the Line component from react-chartjs-2 is properly configured to accept and display this data. You can add more components as needed to display other pieces of data.

DashboardPro.js

This is the advanced version of CoinGecko apis usage and includes more comprehensive analysis of Crypto data

import React, { useEffect, useState } from 'react';
import { makeStyles } from '@material-ui/core/styles';
import { Line } from 'react-chartjs-2';
import axios from 'axios';
const useStyles = makeStyles((theme) => ({
root: {
flexGrow: 1,
},
}));
export default function Dashboard() {
const classes = useStyles();
const [data, setData] = useState({});
useEffect(() => {
const fetchData = async () => {
try {
const result1 = await axios.get('https://api.coingecko.com/api/v3/coins/bitcoin/market_chart?vs_currency=usd&days=1', {
headers: {
'X-CoinGecko-API-Key': 'YOUR_API_KEY'
}
});
// Add more API calls here as needed
setData({
bitcoinMarketChart: result1.data,
// Add more data here as needed
});
} catch (error) {
console.error("Error fetching data", error);
}
};
fetchData();
}, []);
return (
<div className={classes.root}>
{/* Render your charts and other components here using the fetched data */}
</div>
);
}

In this code, I’m using the axios.get() function to make a GET request to the CoinGecko API. The second argument to this function is an options object, where I’m setting the 'X-CoinGecko-API-Key' header to 'YOUR_API_KEY'. This is how you authenticate your requests with your API key. I have included the minimal code here, you can look into the repo for more.

As I mentioned earlier use CGNINJACODER and you can get a 500$ discount to use the premium apis.

Chart.js

This chart displays the crypto charts in various forms

import React, { useEffect, useState } from 'react';
import { Line } from 'react-chartjs-2';
import axios from 'axios';
// Component for the /ping endpoint
export function PingChart() {
const [data, setData] = useState({});
useEffect(() => {
const fetchData = async () => {
try {
const result = await axios.get('https://api.coingecko.com/api/v3/ping');
setData(result.data);
} catch (error) {
console.error("Error fetching data", error);
}
};
fetchData();
}, []);
return (
<div>
<h2>Ping</h2>
{/* Display the data in a structured format */}
<p>{JSON.stringify(data)}</p>
</div>
);
}
// Add more components here for the other endpoints...
// ...
// Component for the /coins/bitcoin/market_chart endpoint
export function BitcoinMarketChart() {
const [data, setData] = useState({});
useEffect(() => {
const fetchData = async () => {
try {
const result = await axios.get('https://api.coingecko.com/api/v3/coins/bitcoin/market_chart?vs_currency=usd&days=1');
setData(result.data);
} catch (error) {
console.error("Error fetching data", error);
}
};
fetchData();
}, []);
return (
<div>
<h2>Bitcoin Market Chart</h2>
{/* Pass the market chart data to the Chart component */}
<Line data={data} />
</div>
);
}

In this code, I’m creating two separate components: PingChart and BitcoinMarketChart. Each component fetches data from a different endpoint when it’s mounted (using the useEffect hook), stores that data in its local state (using the useState hook), and then displays that data. The PingChart component simply displays its data as a string, while the BitcoinMarketChart component passes its data to a Line component from Chart.js to display it as a line chart.

ChartPro.js

This again uses the pro version of Coingeck API’s for the advanced dashboard.

import React, { useEffect, useState } from 'react';
import axios from 'axios';
export function ExclusiveDataComponent() {
const [data, setData] = useState({});
useEffect(() => {
const fetchData = async () => {
try {
const result = await axios.get('https://api.coingecko.com/api/v3/coins/bitcoin/market_chart?vs_currency=usd&days=1', {
headers: {
'X-CoinGecko-API-Key': 'YOUR_API_KEY'
}
});
setData(result.data);
} catch (error) {
console.error("Error fetching data", error);
}
};
fetchData();
}, []);
return (
<div>
<h2>Bitcoin Market Chart</h2>
{/* Pass the market chart data to the Chart component */}
<Line data={data} />
</div>
);
// rest of the code inside repo .............
}

In this code, replace 'https://api.coingecko.com/api/v3/endpoint' with the actual endpoint you want to use, and replace 'YOUR_API_KEY' with your actual API key. This component fetches data when it’s mounted and displays it as a string.

I’m creating separate components: BitcoinMarketChart, BitcoinMarketChartRange, and BinanceTickersChart etc. Each component fetches data from a different endpoint when it’s mounted (using the useEffect hook), stores that data in its local state (using the useState hook), and then displays that data. The BitcoinMarketChart and BitcoinMarketChartRange components pass their data to a Line and Bar component from Chart.js to display it as a line chart and bar chart respectively. The BinanceTickersChart component passes its data to a Doughnut component from Chart.js to display it as a doughnut chart.

App.js

This file is to include both Dashboard.js and ChartPro.js

import React from 'react';
import Dashboard from './Dashboard';
import { BitcoinMarketChart, BitcoinMarketChartRange, BinanceTickersChart } from './ChartPro';
function App() {
return (
<div className="App">
<h1>Crypto Dashboard</h1>
<Dashboard />
<BitcoinMarketChart />
<BitcoinMarketChartRange />
<BinanceTickersChart />
{/* Add more chart components here as needed */}
</div>
);
}
export default App;

In this code, I’m importing the Dashboard component from the Dashboard.js file and the BitcoinMarketChart, BitcoinMarketChartRange, and BinanceTickersChart components from the ChartPro.js file. The App component renders these components inside a div. You can add more chart components as needed.

Conclusion

In conclusion, the Crypto Dashboard is a powerful tool that leverages the CoinGecko API to provide real-time data on various cryptocurrencies. By using technologies like React, Material UI, and Chart.js, it offers a user-friendly interface that makes tracking and analyzing cryptocurrencies a breeze.

The heart of this dashboard is the Dashboard.js file. This file integrates at least 15 APIs from CoinGecko, providing a wealth of information at your fingertips. From current prices to historical data, market caps to trading volumes, the Crypto Dashboard has got you covered.

But the journey doesn’t stop here. The world of cryptocurrencies is constantly evolving, and so is the Crypto Dashboard. With every new feature and improvement, it aims to make cryptocurrency analysis more accessible and understandable for everyone.

So why wait? Dive into the world of cryptocurrencies with the Crypto Dashboard. And remember, use my referral code CGNINJACODERX when signing up for CoinGecko’s premium plan to receive a $500 discount. Happy trading!