🎉 CoinGecko Turns 10! Celebrate with us
Coins: 13,940
Exchanges: 1,057
Market Cap: $2.429T 2.1%
24h Vol: $112.126B
Gas: 16 GWEI
Go Ad-free
API
TABLE OF CONTENTS

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

3.7 | 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.

Each GET request returns a promise that resolves to an array containing the timestamp of the formatted date and the USD price of the coin at that date. If an error occurs during the fetch, the promise resolves to an array containing the timestamp of the formatted date and 0 as a default value. These promises are stored in the promises array.

Promise.all is used to wait for all the promises in the promises array to be resolved. The resolved values form the history array, which is set as the new value for the history state. Finally, loading is set to false to indicate that the data has been fetched.

6. News Component

Let's break down the News.js component.

The NewsTicker component in React is designed to fetch and display cryptocurrency news. It uses the useState hook to manage the state of the news data, loading status, and any errors. When the component is first rendered, the useEffect hook triggers a GET request to the NewsAPI.

If the request is successful, the news articles from the response are stored in the news state variable, and isLoading is set to false. If an error occurs, the error message is stored in the error state variable and isLoading is also set to false.

The component’s return statement handles three scenarios:

  1. If isLoading is true, a loading message is displayed.
  2. If there’s an error (i.e., error is not null), the error message is displayed.
  3. If the news data has been successfully fetched, a Marquee component is returned. This component displays the news articles in a marquee slider. Each article is represented as a link that opens in a new tab and displays the article’s description and published date.

7. The CSS Component

This CSS code styles a cryptocurrency app. It sets global styles like font and specific styles for classes like .App, .news-ticker, and .coin-details. It also styles elements within these classes, like h1 and p within .news-ticker. Additionally, it styles tables and forms elements like select and .ReactDatePicker input. The styles include layout, colors, typography, and interactive states like hover.

8. Rendering the Component

Finally, we render the component:


Running Your React Application in VSCode

Here are the steps to run your React application in Visual Studio Code (VSCode):

  1. Open the Terminal in VSCode: You can open the terminal by going to View > Terminal, or by using the shortcut `Ctrl + ``.

  2. Start the Application: Once all dependencies are installed, you can start your application by running:

npm start

Our application should now be running and accessible at http://localhost:3000 (unless you’ve configured a different port).

The cryptocurrency dashboard builds a user-friendly interface comprising of three key elements:

  1. News Ticker: The NewsTicker component fetches and displays cryptocurrency news. It uses the react-marquee-slider package to create a scrolling news ticker. The news data is fetched from the NewsAPI and each news item is displayed as a clickable link that opens in a new tab.

  2. Portfolio Tracker: This section provides an overview of the user’s cryptocurrency holdings. It displays a pie chart showing the distribution of the user’s holdings across different cryptocurrencies. It also includes a table listing each cryptocurrency the user owns, the amount they own, the current value of their holdings, and the 24-hour price change. The total value of the user’s portfolio, the return on investment (ROI), and the profit and loss (P&L) are also calculated and displayed.

  3. Trends: This section allows the user to select a specific cryptocurrency and view its price trends over a specified date range. The user can select a cryptocurrency from a dropdown menu and specify the date range using two date pickers. Once a cryptocurrency and date range is selected, the CoinDetails component fetches and displays the historical price data for the selected cryptocurrency. The data is displayed as a line chart, with the date on the x-axis and the price on the y-axis.

Crypto Portfolio Tracker with React JS | CoinGecko API

Dynamic Loading

While you interact with the app, behind the scenes, a "loading message" might appear briefly. This simply indicates that the application is diligently fetching data from the CoinGecko API or processing your selections. Once everything is ready, the relevant information and visualizations seamlessly populate your screen, allowing you to delve into your chosen cryptocurrency's performance.

Line chart showing the price fluctuations of Ethereum

The price chart shows the fluctuations of Ethereum’s (ETH) price over a selected time period. The chart captures both current and historical data, providing a comprehensive view of ETH price trends. The x-axis denotes time, and the y-axis denotes the price in USD. The line’s peaks and troughs represent the highs and lows of ETH respectively during the selected time range.

Additionally, there is a performance indicator for the last 24 hours with the price change. If the performance is positive, the indicator is green, and if it’s negative, the indicator is red. The chart provides a visual representation of ETH market performance.

Advanced Functionalities and Useful Endpoints

While this guide covers only basic crypto tracker development, developers who might want to expand tracker functionalities can consider the following:

  • Crypto Market Data: Provide the user with various market data such as market cap, volume, liquidity, dominance, and sentiment on the dashboard using the `/global` and `/coins/markets` endpoints.
  • Crypto Asset Tracking: Implement functionality to track a wider range of crypto assets. This could involve integrating with CoinGecko's `/coins/list` endpoint to fetch a comprehensive list of all available cryptocurrencies.
  • Real-Time Price Updates: Allow users to receive real-time price updates for their specified crypto assets. This would involve interacting with the `/simple/price` endpoint.
  • Historical Data Analysis: Expand the tracker to provide historical price data for different crypto assets. This would allow users to analyze price trends over time using the `/coins/{id}/history` endpoint.
  • Portfolio Analytics: Gain insights with /portfolio/overview to track performance, diversification, and risk.

Developers can consider these endpoints to set up customizable alerts:

  • Price Alerts: Set thresholds for specific coins using `/simple/price` to trigger alerts, and notify the user when the price of a crypto asset reaches a certain level and display it on the dashboard using the `/simple/price` endpoint.
  • Volatility Triggers: Get notified about significant price movements with `/coins/markets/chart ` data analysis.
  • News, Trends & Sentiment: Integrate `/search/trending` and social media analysis for sentiment-based alerts, and display the latest news, trending coins, and popular categories from the crypto space on the dashboard using the `/search/trending` and `/coins/categories/list` endpoints.

You can also use a library like Plotly or Dash to create interactive charts and graphs for your dashboard.

💡Pro-tip: Developing advanced features require familiarizing yourself with the API documentation, understanding the various endpoints you’ll be interacting with, and the specific data each endpoint provides. Always prioritize the accuracy of your tracker's data and adhere to best practices in the crypto industry.

 

Common Issues: Browser’s Security Policies and CORS

When making requests directly from a web browser, such as in a React app, the browser enforces certain security policies that don’t apply when making requests from a command line tool like curl or from a server-side script. This can lead to issues when interacting with APIs that are not set up to support CORS (Cross-Origin Resource Sharing) requests from your app’s origin.

Solution: Setting Up a Server-Side Proxy

To resolve this issue, you can set up a server-side proxy. This involves setting up a server that makes the API requests on behalf of your React app. The React app makes requests to the proxy server, which then makes requests to the API. The proxy server can add the necessary headers to the responses to satisfy the browser’s security policies.

Here are the steps to set up a server-side proxy using Express.js:

  1. Install Node.js and Express.js: First, ensure that Node.js is installed on your machine. Then, create a new directory for your application, initialize a new Node.js application, and install Express.
    mkdir myapp
    cd myapp
    npm init -y
    npm install express

  2. Create Your Server File: Create a new file in your application directory, such as app.js, and start writing your Express.js application. Here’s a basic example of a proxy server setup:

  3. Run Your Express.js Application: Start your Express.js application by running node app.js in your terminal. You should see the message “App is listening on port 3001” in your console.
    In your React app, you would then make requests to your proxy server instead of directly to the API:
    axios.get(`http://localhost:3001/api/v3/coins/${id}/history?date=${formattedDate}`)

Please note that this is a simplified example and might need to be adjusted based on your specific requirements. Also, remember to replace ‘YOUR_API_KEY’ with your actual API key.

Subscribe to a pro API plan - CoinGecko API


Conclusion

And there you have it – you’ve built a comprehensive cryptocurrency price tracker using React JS and the CoinGecko API. Not only does it allow you to monitor real-time prices of your favorite cryptocurrencies but also visualize their historical data. With the skills you’ve learned in this guide, you’re well on your way to creating even more complex and useful applications. Happy coding!

Getting inspiration for other use-cases of our API? Check out this low-code tutorial that walks through how to build an artificial intelligence crypto chatbot.

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
Tell us how much you like this article!
Vote count: 37
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


Explore Polkadot's Ecosystem
Discover trending dApps, wallets, DeFi & more

What is Zeebu?
Learn more about the Web3 neobank


coingecko
Continue in app
Track prices in real-time
Open App
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
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
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
繁體中文
Login to track your favorite coin easily 🚀
By continuing, you agree to CoinGecko Terms of Service and acknowledge you’ve read our Privacy Policy
or
Forgot your password?
Didn't receive confirmation instructions?
Resend confirmation instructions
IT'S FREE! Track your favorite coin easily with CoinGecko 🚀
By continuing, you agree to CoinGecko Terms of Service and acknowledge you’ve read our Privacy Policy
or
Password must contain at least 8 characters including 1 uppercase letter, 1 lowercase letter, 1 number, and 1 special character
Didn't receive confirmation instructions?
Resend confirmation instructions
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