2

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}
    />
    )
});
[...]
1
  • 5
    your removeBox function takes an argument, boxId, but <Button onClick={props.removeItem}/> doesn't call it with a box id Commented Oct 9, 2020 at 15:28

2 Answers 2

4
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

Sign up to request clarification or add additional context in comments.

3 Comments

Thank you, so i have to define the function in the same file and the and then pass the props with the argument the function is expecting up from inside there. OK understood.
There is an alternative -- inside your boxes.map function, you could do something like this instead: removeItem={() => {removeBox(box.id)}}, and keep your Box component as it was
oh ok so i can just pass the function in directly with the argument, that is good to know. I will remember this for next time!
1

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.