Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Passing functions/state variables to a React Component (Arrow notation)

I have a React component that is declared in the arrow-function notation. This component has a child component that is supposed to change the state of the ParentComponent. How can I achieve that? And how would it look like if we passed the change of the state as a function (changeState in this case)?

const ParentComponent = () => {
    const [myState, setMyState] = useState(false);
    const changeState = () => setMyState(!myState);

    return(
        <ChildComponent /> // pass the state variables
    );
}

const ChildComponent = () => { // receive the state variables
    // change state of parent component
}

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

To pass state changes to the child class you can just pass the functions as attributes to the child. This works for any function and you can even just pass in setMyState if you would like into the child function

 const ParentComponent = () => {
    const [myState, setMyState] = useState(false);
    const changeState = () => setMyState(!myState);

    return(
        <ChildComponent 
            changeState={changeState}
        /> // pass the state variables
    );
}

const ChildComponent = ({changeState}) => { // receive the state variables
    // change state of parent component

    // you can use changeState here and 
    // it will update the parent component and rerender the page
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading