I am trying to hide/show components in React based on some state. The main issue I am facing is to maintain the internal state of the components during hiding and showing. The below is the code that does what I expect and maintains the state of each of the components (Africa, Europe, America, Asia):
render() {
const {selectedTab} = this.state;
return (
<div>
<div className={selectedTab === 'africa' ? '' : 'hidden-tab'}><Africa /></div>
<div className={selectedTab === 'europe' ? '' : 'hidden-tab'}><Europe /></div>
<div className={selectedTab === 'america' ? '' : 'hidden-tab'}><America /></div>
<div className={selectedTab === 'asia' ? '' : 'hidden-tab'}><Asia /></div>
</div>
)
}
//regions.scss
.hidden-tab {
display: none
}
However, I am not satisfied with the cleanliness of the above code and would like to refactor, which is where I am facing issues. This is what I have done:
render() {
const {selectedTab} = this.state;
const tabToRegionMap = {
'africa': <Africa />,
'eruope': <Europe />,
'america': <America />,
'asia': <Asia />
};
const {[selectedTab]: selectedRegion, ...regionsToHide} = tabToRegionMap;
return (
<div>
<div className={'hidden-tab'}>
{Object.values(regionsToHide)}
</div>
{selectedRegion}
</div>
);
The above try does show/hide the copmonents but does not maintain the internal state of the components during hiding/showing - it seems like they are being unmounted and remounted every time.
Could anyone please help me solve the problem or suggest a better way of doing it? That would be much appreciated.
PS I would prefer not to move the state to the parent or Redux as there is a lot of boilerplate involved and the states of the individual components are very complex.