React dropdown keeps reseting on tab change
mbkupfer opened this issue · comments
I'm having an issue where my drodown component keeps resetting to its initial state whenever I switch tabs. Any suggestions on how to fix this?
Thanks!
class childComponent extends Component {
constructor(props) {
super(props);
this.state = {
segment: 'All segments'
};
}
handleChange = (e) => {
this.setState(state => ({
segment: e.value
}));
}
render() {
let selectedSegment = this.state.segment
return (
<div>
<Dropdown
options={sorted_segments} // this is just an imported array
value={selectedSegment}
onChange={this.handleChange}
>
</Dropdown>
</div>
In my main app component the childcomponent is declared as such:
<Tabs className='tabs'>
<TabList>
<Tab>Charts</Tab>
</TabList>
<TabPanel>
<childComponent></childComponent>
</TabPanel>
</Tabs>
This happens because, by default, only the children
of the currently active <TabPanel>
are rendered (so they get unmounted — and consequently lose their internal state — when another tab is selected). The easiest solution is to pass forceRenderTabPanel
to <Tabs>
. That way, the component won't be unmounted and its state will be preserved. So:
<Tabs className='tabs' forceRenderTabPanel>
<TabList>
<Tab>Charts</Tab>
</TabList>
<TabPanel>
<YourStatefulComponent/>
</TabPanel>
</Tabs>
You can read about this feature and the related forceRender
prop for <TabPanel>
in the documentation here: https://github.com/reactjs/react-tabs#forcerendertabpanel-boolean.
Perfect, worked like a charm! Thanks for the reply @joepvl