I'm currently accessing the state of a parent component in a child component through the use of callbacks, but I'm not quite sure how it works:
export default function parentComponent({ type }) {
const
[inEditMode, setInEditMode] = useState(false)
return (
<>
<div className={containerCssClasses}>
<childComponent onCancel={() => { setInEditMode(false); }} type={type} />
here, the parent component is calling the child component and passing an anonymous function to the component for it to call back.
In the child component:
function childComponent({onCancel}) {
return (
<div>
<Button onClick={() => onCancel()} variant="link" >
</div?
);
}
I am a bit confused how this is able to work properly if the child component doesn't have access to setInEditMode(). I understand that when passing a function to another function (in this case, a component), it is passed by reference. But does that necessarily mean all of the variables within that function are passed by reference as well? I am new to react (and javascript), but when I looked this concept up I couldn't find a good explanation.
CodePudding user response:
Your implementation is the right way to go. More than callbacks these functions you pass down to child components are call props and I invite you to read the documentation about them.
https://reactjs.org/docs/components-and-props.html
You can also find very detailed articles about it:
https://itnext.io/what-is-props-and-how-to-use-it-in-react-da307f500da0
Whatever you'll pass from the parent to the child can be used in the child component as if it was called in the parent one.
In your case the child is indeed gonna trigger setInEditMode(false)
As you're not passing any variable to it you can actually call it as such:
<Button onClick={onCancel} variant="link" >
CodePudding user response:
The parent component's state you pass to child component as props is not updated as parent's state is changed. so, you need a callback function to access parent's current state at any given time. Also, if you have dependent state value in parent and child component or rather multiple components, you can move it to reducer if you're using redux for state management.