🌐
50 React Coding Puzzles
  • 50 React Coding Puzzles
  • Contact
  • Reviews
  • Table of Contents
  • Introduction
  • 1 - Simple Counter App
  • 2 - Dynamic List of Items with Strikethrough
  • 3 - Color Picker with Hex Code Display
  • 4 - Password Strength Checker
  • 5 - Countdown Timer with Audio
  • 6 - Dynamic Movie List with Filtering and Sorting
  • 7 - Text Animation Component (Fade/Scroll)
  • 8 - Dynamically Generated Text Art
  • 9 - Meme Generator with Custom Text
  • 10 - "What Should I Eat?" Random Recipe Generator
  • 11 - Simple Quiz App with Multiple Choice
  • 12 - Unit Converter
  • 13 - Dynamic Image Gallery with Lightbox
  • 14 - Weather Widget with Temperature and Description
  • 15 - Contact Form with Email and Message Validation
  • 16 - Color Palette Generator
  • 17 - Drag-and-Drop Feature for Rearranging Items
  • 18 - Interactive Quiz with Dynamic Results and Feedback
  • 19 - To-Do List with Task Categorization
  • 20 - Note-Taking App with Markdown Support
  • 21 - Simple Calculator with Basic Operations
  • 22 - Word Scramble Game with Timer and Score
  • 23 - Number Guessing Game
  • 24 - Digital Clock with Time Zone Support
  • 25 - Interactive Time Zone Converter
  • 26 - Weather Forecast App with Location Detection
  • 27 - Real-Time Stock Ticker with Updates
  • 28 - Virtual Dice Roller with Multiple Dice
  • 29 - Responsive Navigation Menu with Dropdowns
  • 30 - Progress Bar for Loading or Task Completion
  • 31 - Modal Window for Alerts and Confirmations
  • 32 - Infinite Scroll for Loading More Content
  • 33 - Form Validation with Error Messages
  • 34 - Search Bar with Filtering and Suggestions
  • 35 - Drag-and-Drop File Upload
  • 36 - Interactive Color Picker with Sliders
  • 37 - Image Carousel with Autoplay
  • 38 - Rating System with Stars or Thumbs Up/Down
  • 39 - Comment Section with Nested Replies
  • 40 - Pagination for Long Lists of Data
  • 41 - Stopwatch app that tracks elapsed time
  • 42 - Responsive E-commerce Product Grid
  • 43 - Random Movie/Book Recommender
  • 44 - Kanban board for managing tasks with drag-and-drop
  • 45 - Chat application with real-time messaging using WebSockets
  • 46 - Calendar that displays events and allows scheduling
  • 47 - Tic-Tac-Toe Game
  • 48 - Hangman Game
  • 49 - Notes App
  • 50 - Expense Tracker
  • Afterword
  • Appendix
Powered by GitBook
On this page
  • Description
  • Algorithm
  • Classes
  • Code
  • Explanation
  • Possible Future Enhancements

27 - Real-Time Stock Ticker with Updates

Description

Create a React application that provides a real-time stock ticker with updates. The ticker should show the ticker symbol, company name, and current market price, update the price automatically at predetermined intervals (e.g., every 5 seconds), highlight price changes with color indicators, and allow users to search for specific stocks by symbol or company name.

Algorithm

  1. Create a state variable to store the stock data.

  2. Define a function to fetch stock data from a financial API.

  3. Define a function to update the stock prices at predetermined intervals.

  4. Define a function to highlight price changes with color indicators.

  5. Define a function to handle user search input.

  6. Render the stock ticker interface.

Classes

  • StockTicker: A component that represents the stock ticker interface.

  • StockDataFetcher: A component that represents the stock data fetching functionality.

  • PriceUpdater: A component that represents the price updating functionality.

  • SearchBar: A component that represents the search bar functionality.

Code

StockTicker.js

import React, { useState, useEffect } from 'react';
import StockDataFetcher from './StockDataFetcher';
import PriceUpdater from './PriceUpdater';
import SearchBar from './SearchBar';

function StockTicker() {
  const [stockData, setStockData] = useState({});
  const [searchQuery, setSearchQuery] = useState('');

  useEffect(() => {
    const fetchStockData = async () => {
      const stockData = await StockDataFetcher.fetchStockData();
      setStockData(stockData);
    };
    fetchStockData();
  }, []);

  useEffect(() => {
    const updatePrices = async () => {
      const updatedStockData = await PriceUpdater.updatePrices(stockData);
      setStockData(updatedStockData);
    };
    const intervalId = setInterval(updatePrices, 5000);
    return () => clearInterval(intervalId);
  }, [stockData]);

  const handleSearchInput = (searchQuery) => {
    setSearchQuery(searchQuery);
  };

  const filteredStocks = stockData.filter((stock) => {
    const tickerSymbol = stock.tickerSymbol.toLowerCase();
    const companyName = stock.companyName.toLowerCase();
    const searchQueryLower = searchQuery.toLowerCase();
    return tickerSymbol.includes(searchQueryLower) || companyName.includes(searchQueryLower);
  });

  return (
    <div>
      <h2>Stock Ticker</h2>
      <SearchBar onSearchInput={handleSearchInput} />
      <ul>
        {filteredStocks.map((stock) => (
          <li key={stock.tickerSymbol}>
            <span>
              {stock.tickerSymbol} ({stock.companyName})
            </span>
            <span>
              {stock.currentPrice} ({stock.priceChange > 0 ? '▲' : '▼'})
            </span>
          </li>
        ))}
      </ul>
    </div>
  );
}

export default StockTicker;

StockDataFetcher.js

import React from 'react';
import axios from 'axios';

function StockDataFetcher() {
  const fetchStockData = async () => {
    const apiURL = `<stock-url>`;
    const response = await axios.get(apiURL);
    const stockData = response.data;
    return stockData;
  };

  return <div />;
}

export default StockDataFetcher;

PriceUpdater.js

import React from 'react';
import axios from 'axios';

function PriceUpdater() {
  const updatePrices = async (stockData) => {
    const updatedStockData = [];
    for (const stock of stockData) {
      const apiURL = `(link unavailable);
      const response = await axios.get(apiURL);
      const currentPrice = response.data.currentPrice;
      const priceChange = currentPrice - stock.currentPrice;
      updatedStockData.push({ ...stock, currentPrice, priceChange });
    }
    return updatedStockData;
  };

  return <div />;
}

export default PriceUpdater;

SearchBar.js

import React from 'react';

function SearchBar({ onSearchInput }) {
  const handleSearchInput = (event) => {
    const searchQuery = event.target.value;
    onSearchInput(searchQuery);
  };

  return (
    <input
      type="search"
      placeholder="Search for a stock"
      onChange={handleSearchInput}
    />
  );
}

export default SearchBar;

Explanation

The StockTicker component renders the stock ticker interface. The StockDataFetcher component fetches stock data from a financial API. The PriceUpdater component updates the stock prices at predetermined intervals. The SearchBar component handles user search input.

Possible Future Enhancements

  • Add more features to the stock ticker, such as charts and news.

  • Improve the user interface and user experience.

Previous26 - Weather Forecast App with Location DetectionNext28 - Virtual Dice Roller with Multiple Dice

Last updated 10 months ago