Last active
September 9, 2024 07:10
-
-
Save jsdevspace/d4ddbe59c1db6f3a678de2469209cd8d to your computer and use it in GitHub Desktop.
TextInput.tsx
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 { ChangeEvent, useState } from 'react'; | |
import Autocomplete from './AutoComplete'; | |
const TextInput = () => { | |
const [tags, setTags] = useState<string[]>([]); | |
const handleKeydown = (e: ChangeEvent<HTMLInputElement> & KeyboardEvent) => { | |
if (e.key !== 'Enter') { | |
return; | |
} | |
const value = e.target.value; | |
if (!value.trim()) { | |
return; | |
} | |
setTags((tags: string[]) => { | |
if (tags.some((tag) => tag.toLowerCase() === value.toLowerCase())) { | |
return [...tags]; | |
} else { | |
return [...tags, value]; | |
} | |
}); | |
e.target.value = ''; | |
}; | |
function removeTag(idx) { | |
setTags(tags.filter((el, i) => i !== idx)); | |
} | |
return ( | |
<div className='text-input-container'> | |
{tags.map((tag, i) => { | |
return ( | |
<div className='tag-item' key={tag + i}> | |
<span className='text'>{tag}</span> | |
<span className='close' onClick={() => removeTag(i)}> | |
× | |
</span> | |
</div> | |
); | |
})} | |
<Autocomplete | |
possibleValues={['test', 'megatest']} | |
handleKeydown={handleKeydown} | |
setTags={setTags} | |
/> | |
</div> | |
); | |
}; | |
export default TextInput; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
TextInput component from the article:
Create a Tags Input Field With Autocomplete in React Without Using Any External Packages