Skip to content

Instantly share code, notes, and snippets.

@madodela
Created October 25, 2022 21:31
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save madodela/4fb8185489fb50d941837bf9ffdcf38a to your computer and use it in GitHub Desktop.
Save madodela/4fb8185489fb50d941837bf9ffdcf38a to your computer and use it in GitHub Desktop.
Creating a basic typeahead with React, Typescript and styled-components
import { useRef, useState } from "react";
import styled from "styled-components";
const Typehahead = styled.input`
width: 300px;
height: 36px;
border-radius: 5px;
padding: 8px;
`;
const DisplayOptions = styled.div`
width: 300px;
height: fit-content;
border: 2px solid black;
border-top: none;
border-radius: 5px;
padding: 8px;
`;
const Wrapper = styled.div`
display: flex;
flex-direction: column;
`;
const Option = styled.div`
display: flex;
height: 32px;
align-items: center;
`;
export const TypeaheadComponent = () => {
const optionsList = ["random word", "random password", "random name"];
const [inputValue, setInputValue] = useState<string>(null);
const [matchedOptions, setMatchedOptions] = useState<string[]>([]);
const typeaheadEl = useRef<HTMLInputElement>(null);
const userTyping = () => {
const value = typeaheadEl.current.value;
setInputValue(value);
// filter the optionList according to the value typed
const options = optionsList.filter((option) => option.includes(value));
setMatchedOptions(options);
};
return (
<Wrapper>
<Typehahead ref={typeaheadEl} onKeyUp={userTyping} />
{!!inputValue && matchedOptions.length > 0 && (
<DisplayOptions>
{matchedOptions.map((option) => {
return <Option>{option}</Option>;
})}
</DisplayOptions>
)}
</Wrapper>
);
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment