Sequence NODE_194
MediumCreate a Tag Input Component
React
JavaScript
Technical Specification
Build an input where user can type a value and press Enter to create a tag, with ability to remove tags.
Input/Output Samples
Input:Type "React" + Enter
Output:Tag 'React' appears
Optimal Logic Path
import { useState } from "react";
function TagInput() {
const [input, setInput] = useState("");
const [tags, setTags] = useState([]);
function onKeyDown(e) {
if (e.key === "Enter") {
e.preventDefault();
const value = input.trim();
if (!value || tags.includes(value)) return;
setTags((prev) => [...prev, value]);
setInput("");
}
}
function removeTag(tag) {
setTags((prev) => prev.filter((t) => t !== tag));
}
return (
<div>
<div>
{tags.map((tag) => (
<span key={tag} onClick={() => removeTag(tag)}>
{tag} ×
</span>
))}
</div>
<input
value={input}
onChange={(e) => setInput(e.target.value)}
onKeyDown={onKeyDown}
placeholder="Type and press Enter"
/>
</div>
);
}Architectural Deep-Dive
We maintain tags in an array and update it when user confirms input via Enter key.