I have a child component that has a save button. However, I can only define the saving function inside the Parent component. I need to pass the function as a props to the child component along with its parameters. All the methods I found uses .this, renders and constructors. I need a way using the modern react functions.
export function childComponent (props) {
let { handleSave, item, list } = props;
return (
//Saves item in list
<button className="palletSaveButton" onClick={handleSave(item, list)}> Save </button>
)
}
const ParentComponent = () => {
let list = [{...}];
let item = {...};
function handleSaveClick(item, list) {
list.push(item)
}
return (
<childComponent handleSave={() => handleSaveClick(item, list)} />
);
}
The difficulty is understanding if you want the list and item to ALWAYS be from the Parent as the source of truth, or if you are trying to pass those variables FROM the child TO the parent.
export function childComponent ({handleSave}) {
return (
//Saves item in list
<button className="palletSaveButton" onClick={handleSave}> Save </button>
)
}
const ParentComponent = () => {
let list = [{...}]
let item = {...}
function handleSaveClick() {
list.push(item)
}
return (
<childComponent handleSave={handleSaveClick} />
);
}
If you simply are looking to click a button on the child, and the logic/values are store in the parent, this should solve your problem. But there's a feeling I'm getting that you are trying to manipulate the variables from the child and send those to the parent.