Item List Manager

Sort by

recency

|

21 Discussions

|

  • + 0 comments

    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

      <ul>
        {items.map((item, index) => (
          <li key={index}>{item}</li>
        ))}
      </ul>
    </div>
    

    ); }

    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.

  • + 0 comments
      const handleAddItem = () => {
        if(!!input.trim()?.length){ // checks on valid input with the !! operator (length > 0) & not empty space
          setItems( items => [...items,input]); // Creates copy of the state, then updates it without mutating the old state directly, this is best practice in react
          setInput(''); // reset the input value
        }
      };
    
    BONUS
            {/* // Additionaly disable the button if there is no valid input */}
            <button onClick={handleAddItem} data-testid="add-button" disabled={!input.trim().length}> 
    BONUS
    
  • + 1 comment
     const handleAddItem = () => {
        setItems(items, items.push(input))
        setInput("")
        console.log(items);
      };
    
  • + 0 comments

    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 } };

  • + 0 comments

    const handleAddItem = () => { if(input.length>0){ setItems([...items,input]) setInput("") } };