Weekly Code Quickies

Build a Live Stock Price Tracker with React, Tailwind CSS & Alpha Vantage API


Listen Later

Looking to build your own real-time stock market tracker app? In this hands-on tutorial, weโ€™ll use React, Tailwind CSS, and the Alpha Vantage API to create a sleek and functional live stock price tracker.

Whether youโ€™re a frontend dev or a beginner trying to get into finance tech, this is a project-based learning opportunity that teaches practical skills while building something useful.

In this project, you'll learn how to:

- Fetch live stock prices from an API using React hooks

- Manage dynamic lists and user input

- Display loading states and error handling

- Style your app with Tailwind CSS for a professional look

Perfect for beginners and intermediate developers looking to boost their React skills!

๐Ÿ› ๏ธ What We'll Build

* ๐Ÿ” A stock search bar with live suggestions

* ๐Ÿ’ฐ A dashboard showing real-time prices

* ๐Ÿ“‰ Dynamic price color change (green/red)

* ๐Ÿ“ฑ Clean Tailwind-powered responsive UI

* ๐ŸŒ API integration with Alpha Vantage (free key!)

๐Ÿš€ Technologies Used

* React + Vite

* Tailwind CSS

* Alpha Vantage API (Get your key)

* React hooks: useState, useEffect, fetch

๐Ÿงฑ Project Setup

bash

CopyEdit

npm create vite@latest stock-tracker --template react cd stock-tracker npm install npm install -D tailwindcss postcss autoprefixer npx tailwindcss init -p

Tailwind Setup (tailwind.config.js):

js

CopyEdit

content: [ "./index.html", "./src/**/*.{js,ts,jsx,tsx}", ],

Tailwind in index.css:

css

CopyEdit

@tailwind base; @tailwind components; @tailwind utilities;

๐Ÿ”— API Setup with Alpha Vantage

Sign up at AlphaVantage.co and grab your API key.

Example fetch call:

js

CopyEdit

const fetchStockPrice = async (symbol) => { const res = await fetch(`https://www.alphavantage.co/query?function=GLOBAL_QUOTE&symbol=${symbol}&apikey=YOUR_KEY`); const data = await res.json(); return data['Global Quote']; };

๐Ÿ“Š Displaying Stock Data

Example JSX:

jsx

CopyEdit

{stockName}

0 ? 'text-green-500' : 'text-red-500'}`}> ${stockPrice} ({priceChange}%)

๐ŸŽจ UI Tips with Tailwind CSS

* Use grid-cols-2 or flex justify-between for layouts

* Add a search input with a dropdown using absolute, bg-white, z-10

* Animate loading state with animate-pulse

๐Ÿ“ฑ Optional Enhancements

* Save recent stock symbols to localStorage

* Add a chart using Chart.js or Recharts

* Show currency, volume, or market cap

Source Code:

import React, { useState, useEffect } from "react";

// StockPrice component fetches and displays the price for a given ticker
function StockPrice({ ticker = "" }) {
const [price, setPrice] = useState(null); // Holds the fetched price
const [loading, setLoading] = useState(true); // Loading state
const [error, setError] = useState(null); // Error state
useEffect(() => {
// Fetch stock price from Alpha Vantage API
const fetchStockPrice = async () => {
try {
setLoading(true);
const apiKey = import.meta.env.VITE_ALPHAVANTAGE_API_KEY; // Uncomment and set your API key
const response = await fetch(
`https://www.alphavantage.co/query?function=GLOBAL_QUOTE&symbol=${ticker}&apikey=${apiKey}`
);
if (!response.ok)
throw new Error(`HTTP error! status: ${response.status}`);
const data = await response.json();
// Check if the API returned a valid price
if (data["Global Quote"] && data["Global Quote"]["05. price"]) {
setPrice(parseFloat(data["Global Quote"]["05. price"]).toFixed(2));
setError(null);
} else {
setError("Could not retrieve price for this ticker.");
setPrice(null);
}
} catch (e) {
setError(`Error fetching data: ${e.message}`);
setPrice(null);
} finally {
setLoading(false);
}
};
fetchStockPrice(); // Call the fetch function when ticker changes
}, [ticker]);
return (

{/* Display the ticker symbol */}
{ticker}
{/* Show loading spinner while fetching */}
{loading && (

Loading price...

)}
{/* Show error message if there is an error */}
{error &&

{error}

}
{/* Show the price if loaded successfully */}
{!loading && !error && price !== null && (

${price}

)}
{/* Show message if no data is available */}
{!loading && !error && price === null && (

No data available.

)}
);
}
// Main StockPriceTracker component manages the list of tickers and input
export default function StockPriceTracker() {
const [tickers, setTickers] = useState(["NVDA", "MSFT", "GOOGL"]); // Initial tickers
const [input, setInput] = useState(""); // Input for new ticker
// Add a new ticker to the list
const addTicker = () => {
const val = input.trim().toUpperCase();
if (val && !tickers.includes(val)) {
setTickers([...tickers, val]);
setInput("");
}
};
return (
{/* App title */}
My Stock Tracker
{/* Input and Add button for new tickers */}
setInput(e.target.value)}
placeholder="Add ticker (e.g. AAPL)"
/>
Add
{/* Display StockPrice components for each ticker */}
{tickers.map((ticker) => (
))}
);
}



Get full access to Norbertโ€™s Web Dev School at norbertbmwebdev.substack.com/subscribe
...more
View all episodesView all episodes
Download on the App Store

Weekly Code QuickiesBy Norbert B.M.