Search code examples
javascriptreactjsreact-hooksreact-component

React change UseState from Child Component


Is it possible to change the value from a useState from inside the child component?

Parent:

const [state, setState] = useState(false);

return <Child func={() => setState(true)}/>

Child:

return <Button onClick={props.func}> Click me to set the state </Button>

It doesn't work this way, is there any way it could work? Thank you


Solution

  • You can do something like this

    //PARENT
    export default function Parent({}) {
      const [state, setState] = useState(false);
            function setParentValue(value){
                 setState(value)
           }
    
            return <Child setValue={setParentValue} />
    
    }
    
    //CHILD
    export default function Child({setValue}) {
      function buttonHandler(){
          setValue('value')
     }
      return <Button onClick={buttonHandler}> Click me to set the state </Button>
    
    }