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
}
CodePudding user response:
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
}
CodePudding user response:
You can pass functions as a prop as well to child components. Try passing the changeState function to the child component like this
const ParentComponent = () => {
const [myState, setMyState] = useState(false);
const changeState = () => setMyState(!myState);
return(
<ChildComponent handleChange={changeState} /> // pass the state variables
);
}
const ChildComponent = ({handleChange}) => { // receive the state variables
// change state of parent component by simply calling
// handleChange as a normal function
}