Skip to content

Instantly share code, notes, and snippets.

@Leowbattle
Created September 21, 2024 23:38
Show Gist options
  • Save Leowbattle/0412d3c8d8cadd65954ac9aed834a32a to your computer and use it in GitHub Desktop.
Save Leowbattle/0412d3c8d8cadd65954ac9aed834a32a to your computer and use it in GitHub Desktop.
function Item({ text, index, removeItem }) {
return (
<div className="todoitem">
<p>{text}</p>
<button onClick={e => removeItem(index)}>X</button>
</div>
);
}
function App() {
const [text, setText] = React.useState("");
const [items, setItems] = React.useState([]);
function buttonclick(e) {
e.preventDefault();
if (e == "") {
return;
}
setItems([...items, text]);
setText("");
}
function removeItem(i) {
setItems([...items.slice(0, i), ...items.slice(i + 1)]);
}
return (
<div>
<input type="text" value={text} onChange={e => setText(e.target.value)} />
<button onClick={buttonclick}>+</button>
<ul>
{items.map((x, i) => <Item text={x} index={i} removeItem={removeItem} />)}
</ul>
</div>
);
}
ReactDOM.render(<App />, document.querySelector("#app"))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment