We use cookies to ensure you have the best browsing experience on our website. Please read our cookie policy for more information about how we use cookies.
- Prepare
- React
- Components
- Item List Manager
- Discussions
Item List Manager
Item List Manager
Sort by
recency
|
23 Discussions
|
Please Login in order to post a comment
import { useState } from "react"; import "h8k-components";
import "./App.css";
function App() { const [items, setItems] = useState([]); const [input, setInput] = useState("");
const handleAddItem = () => { if(input === "") return; setItems([...items, input]); setInput(""); };
return ( <>
Item List
setInput(e.target.value)} placeholder="Enter item" data-testid="input-field" /> Add Item {items.map((item, index) => ( {item} ))} ); }export default App;
The main logic is in this particular method only, just 2 lines of code changes required.
**const handleAddItem = () => { // TODO: Add logic to add input to items list if (input !== "") { setItems((prevItem) => [...prevItem, input]); setInput(""); }
};**
import React, { useState } from "react";
function ItemListManager() { const [items, setItems] = useState([]); const [inputValue, setInputValue] = useState("");
const handleAddItem = () => { if (inputValue.trim() === "") return; // Prevent adding empty items setItems([...items, inputValue]); setInputValue(""); };
return (
Item List Manager
setInputValue(e.target.value)} /> Add Item); }
export default ItemListManager; How it works
Uses useState to manage both the list of items and the input field value.
Adds a new item only if the input is not empty.
Clears the input after successfully adding an item.