paint-brush
How to Create Dynamic Stock Charts in React.jsby@devhubby
128 reads

How to Create Dynamic Stock Charts in React.js

by Kate GlushenkoAugust 1st, 2024
Read on Terminal Reader
Read this story w/o Javascript
tldt arrow

Too Long; Didn't Read

Creating dynamic stock charts can be an exciting way to visualize stock market data in real-time. React.js, with its component-based architecture, is perfect for building such interactive applications. In this article, we'll walk through creating dynamicStock.js and a charting library called `react-chartjs-2'.
featured image - How to Create Dynamic Stock Charts in React.js
 Kate Glushenko HackerNoon profile picture

Creating dynamic stock charts can be an exciting way to visualize stock market data in real-time. React.js, with its component-based architecture, is perfect for building such interactive applications. In this article, we'll walk through creating dynamic stock charts using React.js and a popular charting library called react-chartjs-2 (https://www.npmjs.com/package/react-chartjs-2).

Prerequisites

Before we start, make sure you have the following installed on your machine:

Step 1: Set Up Your React App

First, create a new React application using Create React App:

npx create-react-app stock-chart
cd stock-chart

Step 2: Install Dependencies

We'll need react-chartjs-2 and chart.js to create our charts. Install these packages:

npm install react-chartjs-2 chart.js

Step 3: Fetching Stock Data

To fetch stock data, we'll use the Yahoo API.


Create a file named StockService.js to handle API requests:

// src/StockService.js

import axios from 'axios';

const API_URL = 'https://query1.finance.yahoo.com/v8/finance/chart/';

export const fetchStockData = async (symbol) => {
    const response = await axios.get(`${API_URL}${symbol}?interval=1d&range=1mo`);
    return response.data.chart.result[0];
};

Step 4: Create the Chart Component

Now, let's create a StockChart.js component to display our stock data:

// src/StockChart.js

import React, { useEffect, useState } from 'react';
import { Line } from 'react-chartjs-2';
import { fetchStockData } from './StockService';

const StockChart = ({ symbol }) => {
    const [chartData, setChartData] = useState({});

    useEffect(() => {
        const getStockData = async () => {
            const data = await fetchStockData(symbol);
            const chartData = {
                labels: Object.keys(data),
                datasets: [
                    {
                        label: `${symbol} Stock Price`,
                        data: Object.values(data).map(d => d['4. close']),
                        borderColor: 'rgba(75,192,192,1)',
                        backgroundColor: 'rgba(75,192,192,0.2)',
                    },
                ],
            };
            setChartData(chartData);
        };

        getStockData();
    }, [symbol]);

    return (
        <div>
            <h2>{symbol} Stock Chart</h2>
            <Line data={chartData} />
        </div>
    );
};

export default StockChart;

Step 5: Integrate the Chart Component in App.js

Now, we'll use the StockChart component in our App.js file:

// src/App.js

import React, { useState } from 'react';
import StockChart from './StockChart';

const App = () => {
    const [symbol, setSymbol] = useState('AAPL');

    const handleChange = (e) => {
        setSymbol(e.target.value.toUpperCase());
    };

    return (
        <div className="App">
            <header className="App-header">
                <h1>Stock Market Chart</h1>
                <input
                    type="text"
                    value={symbol}
                    onChange={handleChange}
                    placeholder="Enter stock symbol (e.g., AAPL)"
                />
                <StockChart symbol={symbol} />
            </header>
        </div>
    );
};

export default App;

Step 6: Styling the App

Add some basic styling to App.css:

/* src/App.css */

.App {
  text-align: center;
}

.App-header {
  background-color: #282c34;
  min-height: 100vh;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  font-size: calc(10px + 2vmin);
  color: white;
}

input {
  margin: 20px;
  padding: 10px;
  font-size: 16px;
}

Step 7: Running the Application

Finally, run your application:

npm start


Open your browser and navigate to http://localhost:3000. You should see an input field to enter a stock symbol and a dynamic stock chart displaying the selected stock's price data.

Conclusion

In this tutorial, we created a dynamic stock market chart using React.js and react-chartjs-2. By leveraging the Yahoo Finance API, we fetched real-time stock data and visualized it using a line chart. This setup can be expanded with more features such as additional chart types, more detailed data analysis, and better error handling.


This project can also be integrated into a larger application such as a stock screener or a stock price prediction tool, providing users with powerful insights and interactive visualizations. Happy coding!