I am trying to pass information from a child component up to the parent component, and I want this to happen, whenever the information in the child component changes.
What I have so far does not seem to work. The value of config does get updated in the child component, but the value of data never gets updated in the parent component.
What am I doing wrong?
Here is (a cutdown version of) my parent:
function App() {
const version = process.env.VERSION;
const [data, setData] = React.useState(null)
const childToParent = (childData) => {
setData(childData)
}
console.log(data)
return (
<Container data-testid="containerId" childToParent={childToParent} />
<Footer data-testid="footerId" version={version} config={data} />
);
}
export default App;
and here is (a cutdown version of) my child:
const Container = (childToParent) => {
// config comes from an API call
React.useEffect(() => {
() => childToParent({config});
}, [config]);
return (
<other components/>
)
}
2
Answers
Container
component are not being destructured properly.useEffect
dependency array.Let’s correct these issues:
Container
component, the props need to be destructured properly to accesschildToParent
.App
), you need to pass thechildToParent
function correctly to theContainer
component.With these adjustments, the
config
data from theContainer
component should now properly update thedata
state in the parent (App
) component whenever there’s a change in theconfig
value.At first you have to destructure childToParent from props;
here is the sample code;
or else destructure directly by using Curly Braces