Created
October 25, 2022 21:31
-
-
Save madodela/4fb8185489fb50d941837bf9ffdcf38a to your computer and use it in GitHub Desktop.
Creating a basic typeahead with React, Typescript and styled-components
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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