Skip to content
Advertisement

React component state not updating with passed props

I have created an Accordion component which has data(object) and expanded(boolean) as props. expanded props is used to set the expanded/collapsed state of this component passed as a prop.

JavaScript

Accordion component also has an internal state

JavaScript

which is used for expanding/collapsing the accordion. Below is my complete component

Accordion.jsx

JavaScript

The parent component has a list of data and it loops through the list to create an accordion for each data item.

App.js file

JavaScript

Here goes problem

There is also a button in my App.js file which is for either expanding/collapsing all the accordions together.
But when I pass its value as prop expanded to the accordion component then this value is not getting applied to the internal isExpanded state of the accordion component.

Here is live running code at codesandbox: https://codesandbox.io/s/goofy-nobel-qfxm1?file=/src/App.js:635-745

Advertisement

Answer

Inside the Accordion

JavaScript

This line will take first time(on first render) value. To assign it next time(rerender) value you need to add a effect

JavaScript

And in your case, you can use the props expanded directly inside Accordion, you dont need to take it in local state.

User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement