How to pass key property of a rendered list in React to a function via another HTML tag

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

5

{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>

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;

I suppose you want to delete the item when the user clicks on it, right?
In this case, you seem to have one problem in this button <button key={idx} onClick={(idx) => handleDelete(idx)}>{${idx}}</button>
The idx being passed to onClick function that way is not actually index it is the event element, the event element is where we get the clicked element using event.trigger if you are familiar with it.

To solve this remove idx from the onClick function:

<button key={idx} onClick={() => handleDelete(idx)}>{`${idx}`}</button>

1

Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa Dịch vụ tổ chức sự kiện 5 sao Thông tin về chúng tôi Dịch vụ sinh nhật bé trai Dịch vụ sinh nhật bé gái Sự kiện trọn gói Các tiết mục giải trí Dịch vụ bổ trợ Tiệc cưới sang trọng Dịch vụ khai trương Tư vấn tổ chức sự kiện Hình ảnh sự kiện Cập nhật tin tức Liên hệ ngay Thuê chú hề chuyên nghiệp Tiệc tất niên cho công ty Trang trí tiệc cuối năm Tiệc tất niên độc đáo Sinh nhật bé Hải Đăng Sinh nhật đáng yêu bé Khánh Vân Sinh nhật sang trọng Bích Ngân Tiệc sinh nhật bé Thanh Trang Dịch vụ ông già Noel Xiếc thú vui nhộn Biểu diễn xiếc quay đĩa Dịch vụ tổ chức tiệc uy tín Khám phá dịch vụ của chúng tôi Tiệc sinh nhật cho bé trai Trang trí tiệc cho bé gái Gói sự kiện chuyên nghiệp Chương trình giải trí hấp dẫn Dịch vụ hỗ trợ sự kiện Trang trí tiệc cưới đẹp Khởi đầu thành công với khai trương Chuyên gia tư vấn sự kiện Xem ảnh các sự kiện đẹp Tin mới về sự kiện Kết nối với đội ngũ chuyên gia Chú hề vui nhộn cho tiệc sinh nhật Ý tưởng tiệc cuối năm Tất niên độc đáo Trang trí tiệc hiện đại Tổ chức sinh nhật cho Hải Đăng Sinh nhật độc quyền Khánh Vân Phong cách tiệc Bích Ngân Trang trí tiệc bé Thanh Trang Thuê dịch vụ ông già Noel chuyên nghiệp Xem xiếc khỉ đặc sắc Xiếc quay đĩa thú vị
Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa
Thiết kế website Thiết kế website Thiết kế website Cách kháng tài khoản quảng cáo Mua bán Fanpage Facebook Dịch vụ SEO Tổ chức sinh nhật