React - Best Practice to update parent state in Child component

Viewed 55

I have a bool state in the parent component which gets updated from the child. I want to pass the updated state from parent to child for example if a default value was true in the parent and it got changed from child to false, I want the child also to have the same value for the state variable, currently, it holds previous value only which is true. Please suggest the best approach.

adding code snippet:

Parent.tsx

export default observer(function Parent(){

const [allowPanelToClose,setAllowPanelToClose]= useState(true);

const UpdateSidepanelClose = function (allowClose:boolean)
{
    if(allowClose !== undefined)
    {
        setAllowPanelToClose(allowClose)
    }
}

return(
<Child allowSidepanelToClose = {UpdateSidepanelClose}
 isSidepanelCloseAllowed ={allowPanelToClose}/>

);
})

Child.tsx

export interface ChildProps{
allowSidepanelToClose : (allowClose: boolean) => void;
isSidepanelCloseAllowed : boolean;
}

function Child({
allowSidepanelToClose,
isSidepanelCloseAllowed}:ChildProps){


useKeypress("Escape",() =>{
if(isSidepanelCloseAllowed === false) // isSidepanelCloseAllowed is coming as true which is issue
{
    // do something
}
}


const onBlur = (event: any)=>{
if (!event.currentTarget.contains(event.relatedTarget))
{
    const isValid = somefunction();
}
if(isvalid)
{
    // perform some operation
}
else{
    allowSidepanelToClose(false);//set parent state from true to false
}
}
}




1 Answers

Pass down the state and the setter, so the foo and setFoo. If the child calls setFoo, foo will also be updated.

Also, you should include snippets of your current code when asking a question.

Related