Tag Input With Remove
ReactJS
Medium
6 views
Problem Description
Build a tag input where user can add tags and remove them.
Output Format
Render a React component.
Constraints
Store tags in state, prevent duplicates, and remove on click.
Official Solution
import React, { useMemo, useState } from 'react';
export default function App() {
const [text, setText] = useState('');
const [tags, setTags] = useState(['react', 'hooks']);
const normalized = useMemo(() => text.trim().toLowerCase(), [text]);
function add(e) {
e.preventDefault();
if (!normalized) return;
setTags((prev) => prev.includes(normalized) ? prev : [normalized, ...prev]);
setText('');
}
function remove(t) {
setTags((prev) => prev.filter((x) => x !== t));
}
return (
<div style={{ padding: 16, width: 520 }}>
<h2 style={{ marginTop: 0 }}>meetcode tags</h2>
<form onSubmit={add} style={{ display: 'flex', gap: 10 }}>
<input value={text} onChange={(e) => setText(e.target.value)} placeholder='Add tag' style={{ flex: 1, padding: '10px 12px', borderRadius: 12, border: '1px solid #bbb' }} />
<button type='submit' style={{ padding: '10px 14px', borderRadius: 12, border: 0, background: '#0b5', color: '#fff' }}>Add</button>
</form>
<div style={{ marginTop: 12, display: 'flex', gap: 8, flexWrap: 'wrap' }}>
{tags.map((t) => (
<button key={t} type='button' onClick={() => remove(t)} style={{ padding: '6px 10px', borderRadius: 999, border: '1px solid #ddd', background: '#fff' }}>
{t} ×
</button>
))}
</div>
<div style={{ marginTop: 10, color: '#555' }}>Tip: click a tag to remove it.</div>
</div>
);
}
Solutions (0)
No solutions submitted yet. Be the first!
No comments yet. Start the discussion!