Coins: 18,019
Exchanges: 1,481
Market Cap: $2.495T 0.7%
24h Vol: $87.543B
Gas: 0.036 GWEI
Upgrade to Premium
API
TABLE OF CONTENTS

Developers' Guide: Build an Interactive Crypto Price Tracker with React JS

3.9
| by
Rollend Xavier
-

In this guide, we’ll harness the capabilities of React JS and leverage the CoinGecko API to create a dynamic and feature-rich cryptocurrency price tracker. This tool will allow you to monitor real-time prices of your favorite digital assets and visualize their historical performance.

But why choose React JS over traditional spreadsheet solutions like Google Sheets or Excel? Let’s explore some compelling reasons:

  1. Dynamic Content Rendering: Unlike static spreadsheets, React JS enables dynamic content rendering – crypto price data will automatically update and provide real-time insights without the need to manually refresh or rely on external plugins.
  2. Interactive Charts and Graphs: React JS allows you to integrate interactive charts, graphs, and visualizations seamlessly – whether it’s candlestick charts, line graphs, or pie charts, your price tracker will come alive with rich features that enhance your understanding of market trends.
  3. Automation and Integration: React JS applications effortlessly integrate with APIs and external data sources, streamlining the process and makes it entirely automated, saving you time and effort.

With that, let’s get started!


how to build a crypto portfolio tracker made with React JS

Prerequisites

To follow along, be sure to have the following installed:

  • CoinGecko API: We will be using the CoinGecko API to fetch the market chart data for cryptocurrencies. The CoinGecko API has a free Demo plan accessible to all users with a 30 calls/min rate limit and a monthly cap of 10,000 calls. Sign up for a CoinGecko account and apply for the Demo plan to generate your complimentary API key.
  • Node.js and npm: Node.js is a JavaScript runtime that allows you to run JavaScript on your server or your computer. npm is a package manager for Node.js. You can download both from the official Node.js website.
  • Text Editor or IDE: You will need a text editor or an Integrated Development Environment (IDE) to write your code. Some popular choices include Sublime Text, Atom, Visual Studio Code, and PyCharm. I will be using Visual Studio Code as the IDE, which is smart, fast and customizable IDE available in the market.

Set Up Your Project

Create a new React project using create-react-app:

npx create-react-app crypto-tracker
cd crypto-tracker

Create a new React project using create-react-app:

Install Required Libraries

Our application will use several libraries:

  • axios: A promise-based HTTP client for making requests to our API.
  • recharts: A charting library built on React components, for visualizing our data.
  • react-datepicker: A date picker component for React, for selecting the date range of our historical data.

To install these libraries, navigate to your project directory in your terminal and run the following commands:

npm install axios recharts react-datepicker

npm install axios recharts react-datepicker

This will install the libraries and add them to your package.json file.

💡Pro-tip: Remember to replace the API key placeholder with your own CoinGecko API key before running the application.

 

Interactive Crypto Price Tracker - Complete Code in React JS

The following is our complete code for the crypto price tracker, written in React JS, a popular JavaScript library for building user interfaces. The app.js file, which we’ll delve into, is the heart of our application. It contains the main components and the logic that ties everything together.

For a detailed view of the code, please refer to the provided GitHub repository: https://github.com/rollendxavier/crypto-portfolio-tracker-react

While the code may seem complex at first glance, don’t worry! We’ll unpack it in the following sections.

1. Importing Libraries and Styles

First, we import the necessary libraries and styles.

We’re importing React, useState, useEffect, and useMemo from the react library. useState, useEffect, and useMemo are hooks that allow us to use state and other React features in functional components. We’re also importing axios for making HTTP requests, several components from recharts for creating our line and pie charts, and DatePicker for our date picker component. 

Lastly, we’re importing NewsTicker from our local components for displaying news updates. Finally, we’re importing the CSS for react-datepicker and our own custom CSS.

2. The CoinDetails Component

The CoinDetails component displays the details of a selected coin.

This component receives a coin object and a history array as props. The coin object contains the details of the selected coin, and the history array contains the historical price data of the coin. The chartData constant is created by mapping over the history array and transforming each data point into an object with date and price properties. This data is then used to create a line chart using the LineChart component from recharts. 

The priceChangeColor constant is determined based on whether the 24-hour price change is less than 0, which would make it red, otherwise, it's green. This color is used to visually indicate whether the price has increased or decreased. The component returns a div containing the coin's name and symbol, the price change percentage, the current price, and the line chart of the historical data.

3. The App Component

The App component is the main component of our application.

In the App function, we’re using several state variables:

  • coins is an array that will hold the list of all coins fetched from the API.
  • selectedCoin is an object that will hold the details of the currently selected coin.
  • history is an array that will hold the historical price data of the selected coin.
  • loading is a boolean that indicates whether the data is currently being fetched from the API.
  • startDate and endDate are date objects that represent the selected date range for the historical data.
  • api_key is a string that holds your CoinGecko API key.

Additionally, we’re using the useState hook from React to manage these state variables. Each state variable has a corresponding setter function (like setCoins for coins) that we can use to update its value. The initial value of each state variable is set in the call to useState.

4. Fetching the Coin Data

We use the useEffect hook to fetch the coin data from the API when the component mounts:

We’re making a GET request to the /coins/markets endpoint of the CoinGecko API. The vs_currency=usd query parameter specifies that we want the coin prices in USD. The ids query parameter is used to specify the ids of the coins we’re interested in, which are obtained by mapping over the holdings array and joining the ids with commas. The headers option is used to pass our API key in the request headers. When the response is received, we map over the holdings array, and for each holding, we find the corresponding coin in the response data. We then return a new object that spreads the properties of the holding and adds the name, current_price, price_change_24h, and price_change_percentage_24h from the coin data. The result is an array of updated holdings, which we set as the new value for the coins state. We also set loading to false to indicate that the data has been fetched. If an error occurs during the fetch, we log the error message to the console.

5. Handling Coin Selection

The handleCoinSelect function is called when a coin is selected from the dropdown:

The handleCoinSelect function receives the id of the selected coin. It finds the coin in the coins array and sets it as the selectedCoin. It then sets loading to true to indicate that data is being fetched.

The function fetches the historical price data for the selected coin for the last 5 years. It does this by making a GET request to the /coins/{id}/history endpoint of the CoinGecko API for each year. The date query parameter is used to specify the date for which we want the historical data. The date is formatted and decremented by one year in each iteration of the loop.

CoinGecko's Content Editorial Guidelines
CoinGecko’s content aims to demystify the crypto industry. While certain posts you see may be sponsored, we strive to uphold the highest standards of editorial quality and integrity, and do not publish any content that has not been vetted by our editors.
Learn more
Want to be the first to know about upcoming airdrops?
Subscribe to the CoinGecko Daily Newsletter!
Join 600,000+ crypto enthusiasts, traders, and degens in getting the latest crypto news, articles, videos, and reports by subscribing to our FREE newsletter.
Tell us how much you like this article!
Vote count: 43
Rollend Xavier
Rollend Xavier
Rollend is a Microsoft Certified Cloud Architect with 16 years of experience. He is the author of the book “Automate Your Life: Streamline Your Daily Tasks with Python: 30 Powerful Ways to Streamline Your Daily Tasks with Python”. Follow the author on Twitter @RollendXavier

Related Articles

New Portfolio
Icon & name
Select Currency
Suggested Currencies
USD
US Dollar
IDR
Indonesian Rupiah
TWD
New Taiwan Dollar
EUR
Euro
KRW
South Korean Won
JPY
Japanese Yen
RUB
Russian Ruble
CNY
Chinese Yuan
Fiat Currencies
AED
United Arab Emirates Dirham
ARS
Argentine Peso
AUD
Australian Dollar
BDT
Bangladeshi Taka
BHD
Bahraini Dinar
BMD
Bermudian Dollar
BRL
Brazil Real
CAD
Canadian Dollar
CHF
Swiss Franc
CLP
Chilean Peso
CZK
Czech Koruna
DKK
Danish Krone
GBP
British Pound Sterling
GEL
Georgian Lari
HKD
Hong Kong Dollar
HUF
Hungarian Forint
ILS
Israeli New Shekel
INR
Indian Rupee
KWD
Kuwaiti Dinar
LKR
Sri Lankan Rupee
MMK
Burmese Kyat
MXN
Mexican Peso
MYR
Malaysian Ringgit
NGN
Nigerian Naira
NOK
Norwegian Krone
NZD
New Zealand Dollar
PHP
Philippine Peso
PKR
Pakistani Rupee
PLN
Polish Zloty
SAR
Saudi Riyal
SEK
Swedish Krona
SGD
Singapore Dollar
THB
Thai Baht
TRY
Turkish Lira
UAH
Ukrainian hryvnia
VEF
Venezuelan bolívar fuerte
VND
Vietnamese đồng
ZAR
South African Rand
XDR
IMF Special Drawing Rights
Cryptocurrencies
BTC
Bitcoin
ETH
Ether
LTC
Litecoin
BCH
Bitcoin Cash
BNB
Binance Coin
EOS
EOS
XRP
XRP
XLM
Lumens
LINK
Chainlink
DOT
Polkadot
YFI
Yearn.finance
SOL
Solana
Bitcoin Units
BITS
Bits
SATS
Satoshi
Commodities
XAG
Silver - Troy Ounce
XAU
Gold - Troy Ounce
Select Language
Popular Languages
EN
English
RU
Русский
DE
Deutsch
PL
język polski
ES
Español
VI
Tiếng việt
FR
Français
PT-BR
Português
All Languages
AR
العربية
BG
български
CS
čeština
DA
dansk
EL
Ελληνικά
FI
suomen kieli
HE
עִבְרִית
HI
हिंदी
HR
hrvatski
HU
Magyar nyelv
ID
Bahasa Indonesia
IT
Italiano
JA
日本語
KO
한국어
LT
lietuvių kalba
NL
Nederlands
NO
norsk
RO
Limba română
SK
slovenský jazyk
SL
slovenski jezik
SV
Svenska
TH
ภาษาไทย
TR
Türkçe
UK
украї́нська мо́ва
ZH
简体中文
ZH-TW
繁體中文
Welcome to CoinGecko
Welcome back!
Login or Sign up in seconds
or
Sign in with . Not you?
Forgot your password?
Didn't receive confirmation instructions?
Resend confirmation instructions
Password must contain at least 8 characters including 1 uppercase letter, 1 lowercase letter, 1 number, and 1 special character
By continuing, you acknowledge that you've read and agree fully to our Terms of Service and Privacy Policy.
Get Price Alerts with CoinGecko App
Forgot your password?
You will receive an email with instructions on how to reset your password in a few minutes.
Resend confirmation instructions
You will receive an email with instructions for how to confirm your email address in a few minutes.
Get the CoinGecko app.
Scan this QR code to download the app now App QR Code Or check it out in the app stores
Add NFT
Track wallet address
Paste
We only display assets from supported networks.
Ethereum Mainnet
Base Mainnet
BNB Smart Chain
Arbitrum
Avalanche
Fantom
Flare
Gnosis
Linea
Optimism
Polygon
Polygon zkEVM
Scroll
Stellar
Story
Syscoin
Telos
X Layer
Xai
Read-only access
We only fetch public data. No private keys, no signing, and we can't make any changes to your wallet.
Create Portfolio
Select icon
💎
🔥
👀
🚀
💰
🦍
🌱
💩
🌙
🪂
💚
CoinGecko
Better on the app
Real-time price alerts and a faster, smoother experience.
You’ve reached the limit.
Guest portfolios are limited to 10 coins. Sign up or log in to keep the coins listed below.