Below is the code for making an input box to both the search and select box
const CreateArticle = () => {
const [tags, setTags] = useState([]);
const [searchTerm, setSearchTerm] = useState(”);
const [selectedTags, setSelectedTags] = useState([]);
const [activeTab, setActiveTab] = useState(“create”); // “create” or “preview”
const [newTag, setNewTag] = useState(”);
/* Tag section*/
// Filter tags based on the search term
const filteredTags = tags.filter((tag) =>
tag.name.toLowerCase().includes(searchTerm.toLowerCase())
);
const handleTagSearch = (searchTerm) => {
setSearchTerm(searchTerm);
};
const handleTagSelection = (tagId) => {
// Add or remove the selected tag based on whether it’s already selected
setSelectedTags((prevTags) =>
prevTags.includes(tagId)
? prevTags.filter((id) => id !== tagId)
: […prevTags, tagId]
);
// Clear the input field after selecting a tag
setSearchTerm(”);
};
const handleTagInputKeyPress = (e) => {
if (e.key === ‘Enter’ && searchTerm.trim() !== ”) {
// Check if the entered tag is already present in the selectedTags array
const existingTag = tags.find((tag) => tag.name.toLowerCase() === searchTerm.toLowerCase());
if (existingTag && !selectedTags.includes(existingTag.id)) {
// If the tag already exists, select it
handleTagSelection(existingTag.id);
} else if (!existingTag && !selectedTags.includes(searchTerm)) {
// If not present, add it to the selectedTags array
setSelectedTags([…selectedTags, searchTerm]);
}
// Clear the input field after adding a tag
setSearchTerm(”);
}
};
const handlePreview = () => {
setPreviewContent({ title, content, selectedCategory, selectedTags });
};
/* Tag section ends*/
return (
{/* Tag section by MUKIL */}
<div className=“create-article__checkbox-container”>
<label className=“create-article__label”>Select Tags:</label>
<br />
<div className=“create-article__selected-tags”>
{selectedTags.map((tagId) => (
<div key={tagId} className=“create-article__selected-tag”>
{typeof tagId === ‘number’
? tags.find((tag) => tag.id === tagId)?.name
: tagId}
<button
type=“button”
onClick={() => handleTagSelection(tagId)}
className=“create-article__tag-remove-button”
>
<span className=“close-button”>
? {/* Close (X) symbol */}
</span>
</button>
</div>
))}
</div>
<div className=“create-article__tag-search”>
<input
type=“text”
placeholder=“Search tags…”
onChange={(e) => handleTagSearch(e.target.value)}
value={searchTerm}
onKeyPress={handleTagInputKeyPress}
className=“create-article__tag-input”
/>
</div>
{searchTerm && filteredTags.length > 0 && (
<div className=“create-article__tag-scroll-container”>
<div className=“create-article__all-tags”>
{filteredTags.map((tag) => (
<div
key={tag.id}
className=“create-article__checkbox”
onClick={() => handleTagSelection(tag.id)}
>
<label htmlFor={`tag-${tag.id}`}>
{he.decode(tag.name)}
</label>
</div>
))}
</div>
</div>
)}
</div>
{/* Tag section ends */}
);
};
export default CreateArticle;