I have researched this topic for quite some time now, yet I still cannot make the ‘Remove’ button in the child component (ControlledOpenSelect) only remove the item with the key it was passed – by using the callback function.
My ControlledOpenSelect (the child component):
const example={'skittle':10,"carrots":20,"cars":50,"potatoes":30} export default function ControlledOpenSelect({ourObject=example,onRemove,key}) { const classes = useStyles(); const [open, setOpen] = React.useState(false); const [product,setProduct]=React.useState('None') const [quantity,setQuantity]=React.useState(0) const [price,setPrice]=React.useState('') const [subTotal,setSubTotal]=React.useState(0) const handleChange = (event) => { setProduct(event.target.value); }; const handleClose = () => { setOpen(false); }; const handleOpen = () => { setOpen(true); }; const handleQuantity=(event)=>{ setQuantity(event.target.value) } //const productList=Object.keys(ourObject) //const correct_price=ourObject[product] //React.useEffect(()=>{ //setPrice(correct_price) //},[correct_price]) //React.useEffect(()=>{ //setSubTotal(price*quantity) //},[quantity,product,price]) return ( <div> <Button className={classes.button} onClick={handleOpen}> Open the select </Button> <FormControl className={classes.formControl}> <InputLabel id="demo-controlled-open-select-label">Product</InputLabel> <Select labelId="demo-controlled-open-select-label" id="demo-controlled-open-select" open={open} onClose={handleClose} onOpen={handleOpen} value={product} onChange={handleChange} > {productList.map( item => <MenuItem value={item}>{item}</MenuItem> )} </Select> <div> <TextField id="outlined-basic" label="Quantity" variant="outlined" onChange={handleQuantity}/> <TextField id="outlined-basic" label="Price" variant="outlined" value={price} /> <p>{subTotal}</p> </div> </FormControl> <button onClick={()=>onRemove(key)}>Remove</button> </div> ); }
My parent component FullComponent:
const example={'skittle':10,"carrots":20,"cars":50,"potatoes":30} const FullComponent=({ourObject=example})=>{ const [add,setAdd]=React.useState([]) // const [remove,setRemove]=React.useState([]) const id=React.useState(_uniqueId('prefix-')); const handleClick=(event)=>{ setAdd([...add, <ControlledOpenSelect ourObject={ourObject} id={id}/>]) } const handleRemove=(id)=>{ const newAdd=add.filter((item)=> item.id !== id) setAdd(newAdd) } return ( <> {add.map((item)=>{ return ( <> <ControlledOpenSelect ourObject={ourObject} key={item.id} onRemove={handleRemove} /> </> ) })} <button type="button" onClick={handleClick}>Add</button> </> ) } export default FullComponent
Thank you so much!
Advertisement
Answer
You are not passing the id to the handleRemove method . you need to pass an inline function which passes the item.id as argument
onRemove={() => handleRemove(item.id)}