Todo List Add And Remove
ReactJS
Medium
4 views
Problem Description
Create a todo list where you can add items and remove them.
Output Format
Render a React component.
Constraints
Store items in state and update immutably.
Official Solution
import React, { useState } from 'react';
export default function App() {
const [text, setText] = useState('');
const [items, setItems] = useState([{ id: 1, title: 'Solve one meetcode question' }]);
function add(e) {
e.preventDefault();
const t = text.trim();
if (!t) return;
setItems((prev) => [{ id: Date.now(), title: t }, ...prev]);
setText('');
}
function remove(id) {
setItems((prev) => prev.filter((x) => x.id !== id));
}
return (
<div style={{ padding: 16, width: 520 }}>
<h2 style={{ marginTop: 0 }}>meetcode todos</h2>
<form onSubmit={add} style={{ display: 'flex', gap: 10 }}>
<input value={text} onChange={(e) => setText(e.target.value)} placeholder='Add a task' 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>
<ul style={{ marginTop: 14, paddingLeft: 18 }}>
{items.map((it) => (
<li key={it.id} style={{ marginBottom: 8 }}>
{it.title}{' '}
<button type='button' onClick={() => remove(it.id)} style={{ marginLeft: 10, padding: '4px 10px', borderRadius: 999, border: '1px solid #ddd', background: '#fff' }}>Remove</button>
</li>
))}
</ul>
</div>
);
}
Solutions (0)
No solutions submitted yet. Be the first!
No comments yet. Start the discussion!