Official Solution
import React, { useState } from 'react';
export default function App() {
const [text, setText] = useState('');
const [items, setItems] = useState(['React']);
const [history, setHistory] = useState([]);
function add() {
const t = text.trim();
if (!t) return;
setHistory((h) => [items, ...h].slice(0, 5));
setItems((prev) => [t, ...prev]);
setText('');
}
function undo() {
setHistory((h) => {
if (!h.length) return h;
const [prev, ...rest] = h;
setItems(prev);
return rest;
});
}
return (
<div style={{ padding: 16, width: 420 }}>
<h2 style={{ marginTop: 0 }}>meetcode quick add</h2>
<div 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='button' onClick={add} style={{ padding: '10px 14px', borderRadius: 12, border: 0, background: '#0b5', color: '#fff' }}>Add</button>
</div>
<button type='button' onClick={undo} disabled={!history.length} style={{ marginTop: 10, padding: '8px 12px', borderRadius: 12, border: '1px solid #ddd', background: '#fff', opacity: history.length ? 1 : 0.6 }}>Undo</button>
<ul style={{ marginTop: 12, paddingLeft: 18 }}>
{items.map((x) => <li key={x}>{x}</li>)}
</ul>
</div>
);
}
No comments yet. Start the discussion!