onClick function does not remove item in an array

Viewed 59

I have a button which when you click should remove a box from the list but it doesn't work. Can anyone see why?

const Box = (props) => {
    return (
        <>
            <div id={props.id} style={{height:`${props.height}em`, width:`${props.width}em`, backgroundColor: props.color }}>
             </div>
           <Button onClick={props.removeItem}/>
        </>

    );
};
export default Box;
const BoxList = () => {

const [boxes, setBoxes] = useState([{height: "", width:"", color:"", id:""}]);

const removeBox = (boxId) => {
   const updatedBoxList = boxes.filter(box => box.id !== boxId);
    setBoxes(updatedBoxList);  // this is where the update should happen
};

const boxesArray = boxes.map((box) => {
    return(
    <Box width={box.height}
         height={box.width}
         color={box.color}
         id={box.id}
         removeItem={removeBox}
    />
    )
});
[...]
2 Answers
const Box = (props) => {
    const removeItem = () => {
        props.removeItem(props.id);
    };
    return (
        <>
            <div id={props.id} style={{height:`${props.height}em`, width:`${props.width}em`, backgroundColor: props.color }}>
             </div>
           <Button onClick={removeItem}/>
        </>

    );
};
export default Box;

I've redefined your Box component so that it calls the props.removeItem function with the argument the function is expecting

You need to pass the boxId into removeItem. Right now it is being called with the click event as its argument.

Related