Skip to content

Instantly share code, notes, and snippets.

@kylealwyn
Last active November 13, 2019 22:49
Show Gist options
  • Save kylealwyn/0cedf829b4d8acb0950f0e7b469a7404 to your computer and use it in GitHub Desktop.
Save kylealwyn/0cedf829b4d8acb0950f0e7b469a7404 to your computer and use it in GitHub Desktop.

Typeahead

We're building an open source Typeahead component that will be published to NPM and also used internally. We want to give each team flexibility on how the list options are provided as well as styling the input and list options.

Requirements are as follows:

  1. Teams using the Typeahead component need to be able to provide either a local or remote list of options
    • Example: One team is using our component to filter through a local array of US states and another team is using it to search for users by first and last name via an API endpoint
  2. Teams using our Typeahead component must have the ability to render custom options
    • Example: Our consumer team needs an icon in the option row but our clinical team does not

Bonus:

  • How do we prevent hammering our servers when users are typing quickly?
  • How do we ensure we're showing the results of the latest query when using a remote data source?

img

import React from "react";
import ReactDOM from "react-dom";


async function searchFood(query) {
  return ['Apple', 'Oranges', 'Bananas', 'Pasta', 'Chocolate'].filter(item =>
    item.toLowerCase().includes(query.toLowerCase())
  );
}

async function searchGithubUsers(query) {
  if (!query) {
    return [];
  }

  const { items } = await (await fetch(
    `https://api.github.com/search/users?q=${query}`,
    {
      headers: {
        Authorization: "token <insert-token>"
      }
    }
  )).json();

  return items;
}

function Typeahead() {
  return (
    <div className="typeahead">
      <input
	className="typeahead-input"
        placeholder="Search here..."
      />

      <div className="typeahead-options"></div>
    </div>
  );
}

function App() {
  return (
    <div className="App">
      <Typeahead />
    </div>
  );
}

const rootElement = document.getElementById("root");
ReactDOM.render(<App />, rootElement);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment