Search code examples
reactjsreact-propsarrow-functions

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

  • 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
    }