Snips & Tips
Snips & Tips
  • Snips & Tips
  • 📊Data Science
    • Polars Dataframe Library
    • Loading large data
    • Pandas
      • Pandas Apply Function
    • Apache Spark
      • Custom Transformer
    • Data Visualizations
    • Jupyter Notebooks
      • Jupyter Notebook Structure
    • Probability
    • Statistics
      • Statistical Tests
      • Z - Test
      • Hypothesis Testing
    • SQL
      • SQL Tips
      • Creating new columns
  • ☘️Deep Learning
    • Backpropagation in Deep Learning
    • Pytorch Early Stopping
    • Optimizers
  • Pytorch Tensor Shapes
  • 🔖Machine Learning
    • Handling Imbalanced Dataset
    • Time Series Forecasting
      • Hierarchical Time Series Forecasting
      • Facebook Prophet
      • Misc
    • Handling high dimensionality data
      • Weight of evidence and Information value
    • Debugging ML Models
    • Feature Engineering
      • Time Series
      • Outlier Detection
      • Categorical Encoding
      • Feature Scaling
  • 🐲DSA
    • Arrays
  • 🖥️WEB DEV
    • Typescript
    • React State Management
    • Redux Boilerplate
    • Intercept a HTTP request or response
    • this keyword
    • Array Methods
    • Throttle Debounce
    • Media Queries
    • React Typeahead Search
  • Replace text with React Component
  • 💻Product Analytics
    • Product Sense
    • Customer Segmentation
  • 🖥️Terminal
    • Terminal Commands
    • Jupyter Notebook 2 HTML
  • 🪛Tools and Libraries
    • Web Based
    • Databases
  • 🚟Backend
    • Fast API CRUD
    • Scalable APIs
  • 💸Quant Finance
    • Misc
    • Factor Investing
  • 🎮Game Dev
    • Misc
  • 🛠️Architecture
    • Docker
    • AWS CDK
  • 🦠Artificial Intelligence
    • AI Engg
Powered by GitBook
On this page

Was this helpful?

Edit on GitHub
  1. WEB DEV

React Typeahead Search

import { useState } from "react";

const allCities = [
  {
    city: "New York",
    val: "www.newyork.com",
  },
  {
    city: "New York City",
    val: "www.newyorkcity.com",
  },
  {
    city: "Rome",
    val: "www.rome.com",
  },
  {
    city: "RomeCity",
    val: "www.romecity.com",
  },
];

export default function App() {
  const [cities, setCities] = useState([]);
  const [selectedCity, setSelectedCity] = useState({});

  const handleChange = (e) => {
    console.log(e.target.value);
    input = e.target.value;

    if (input.trim()) {
      try {
        // Create a regex to match city names starting with the input
        const regex = new RegExp(`^${input}`, "i");
        const filteredCities = allCities.filter((city) =>
          regex.test(city.city)
        );
        setCities(filteredCities);
      } catch (err) {
        console.error("Invalid regex input:", err.message);
        setCities([]);
      }
    } else {
      setCities([]);
    }
  };

  return (
    <div className="App">
      <input onChange={(e) => handleChange(e)} />
      <ul>
        {cities.map((city) => {
          return (
            <li key={city.city}>
              {city.city}
              <button onClick={() => setSelectedCity(city)}>set city</button>
            </li>
          );
        })}
      </ul>
      <div>Selected city</div>
      {selectedCity && (
        <div>
          {selectedCity.city}, {selectedCity.val}{" "}
        </div>
      )}
    </div>
  );
}
PreviousMedia QueriesNextReplace text with React Component

Last updated 5 months ago

Was this helpful?

🖥️