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
|
21 Discussions
|
Please Login in order to post a comment
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.
const handleAddItem = () => { if (input.trim() !== "") { // Prevent adding empty or only-space items setItems([...items, input]); // Add the input to the list setInput(""); // Clear the input field } };
const handleAddItem = () => { if(input.length>0){ setItems([...items,input]) setInput("") } };