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:
- 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.
- 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.
- 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!
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
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
This will install the libraries and add them to your package.json file.
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:
-
coinsis an array that will hold the list of all coins fetched from the API. -
selectedCoinis an object that will hold the details of the currently selected coin. -
historyis an array that will hold the historical price data of the selected coin. -
loadingis a boolean that indicates whether the data is currently being fetched from the API. -
startDateandendDateare date objects that represent the selected date range for the historical data. -
api_keyis 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.
Subscribe to the CoinGecko Daily Newsletter!
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