skip to Main Content

How to pass the Key value of each list item via the button created inside the li tag to the function, so that i cant filter that element out and render new list.
Need to complete the handleDelete function

import { useState } from "react";

function MyComponent() {
    const [foods, setFoods] = useState(["Apple", "Orange", "Banana"])

    const handleSubmit = () => {
        const newFood = document.getElementById("input-fruit").value;
        document.getElementById("input-fruit").value = "";
        setFoods(prevFoods => ([...prevFoods, newFood]))
    }

    const handleDelete = (idx) => {
        console.log(idx);

        // setFoods(foods.filter((el, idx) => console.log(idxx, idx)))
    }
    return (<>
        <ul>
            {foods.map((el, idx) => <li key={idx}> {el} <button key={idx} onClick={(idx) => handleDelete(idx)}>{`${idx}`}</button> </li>)}
        </ul>

        <input id="input-fruit" type="text" placeholder="Enter a food item" />
        <button onClick={handleSubmit}>Submit</button>
    </>);
}

export default MyComponent

2

Answers


  1. {foods.map((el, idx) => <li key={idx}> {el} <button key={idx} onClick={(idx) => handleDelete(idx)}>{`${idx}`}</button> </li>)}
    

    You’re using the map callback as el and idx, but you’re defining the onClick arrow function as (idx) =>.

    The onClick will get the click event as first param, but you’re overwriting that.

    If you don’t need the click event, just use an empty arrow () =>

    {
        foods.map((el, idx) => (
            <li key={idx}> 
                {el} 
                <button key={idx} onClick={() => handleDelete(idx)}>{`${idx}`}</button> 
            </li>
         )
    }
    

    For the handleDelete function, you can splice the array to remove it by index:

    const { useState } = React;
    
    function MyComponent() {
        const [foods, setFoods] = useState(["Apple", "Orange", "Banana"])
    
        const handleSubmit = () => {
            const newFood = document.getElementById("input-fruit").value;
            document.getElementById("input-fruit").value = "";
            setFoods(prevFoods => ([...prevFoods, newFood]))
        }
    
        const handleDelete = (idx) => {
            setFoods(prev => {
                let cpy = [...prev];
                cpy.splice(idx, 1);
                return cpy;
            })
        }
        return (<React.Fragment>
            <ul>
                {foods.map((el, idx) => <li key={idx}> {el} <button key={idx} onClick={() => handleDelete(idx)}>{`${idx}`}</button> </li>)}
            </ul>
    
            <input id="input-fruit" type="text" placeholder="Enter a food item" />
            <button onClick={handleSubmit}>Submit</button>
        </React.Fragment>);
    }
    
    ReactDOM.render(<MyComponent />, document.getElementById("react"));
    <script src="https://cdnjs.cloudflare.com/ajax/libs/react/17.0.1/umd/react.production.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/17.0.1/umd/react-dom.production.min.js"></script>
    <div id="react"></div>
    Login or Signup to reply.
  2. The onClick handler is updated to onClick={() => handleDelete(idx)}. This ensures the correct index is passed when the button is clicked.

    Inside handleDelete, the setFoods function filters out the item at the specified index.

    The filter function compares the current index of the item (index) with the index you want to delete (idx). If they don’t match, the item remains in the array.

    You don’t need to set a key on the button itself; it’s only necessary for the li elements to maintain uniqueness in the rendered list.

    
    import { useState } from "react";
    
    function MyComponent() {
        const [foods, setFoods] = useState(["Apple", "Orange", "Banana"]);
    
        const handleSubmit = () => {
            const newFood = document.getElementById("input-fruit").value;
            document.getElementById("input-fruit").value = "";
            setFoods(prevFoods => [...prevFoods, newFood]);
        };
    
        const handleDelete = (idx) => {
            setFoods(foods.filter((_, index) => index !== idx));
        };
    
        return (
            <>
                <ul>
                    {foods.map((el, idx) => (
                        <li key={idx}>
                            {el} <button onClick={() => handleDelete(idx)}>Delete</button>
                        </li>
                    ))}
                </ul>
    
                <input id="input-fruit" type="text" placeholder="Enter a food item" />
                <button onClick={handleSubmit}>Submit</button>
            </>
        );
    }
    
    export default MyComponent;
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search