I am trying to implement a minimize/maximize feature in React. I have a div
that serves as an information panel and by clicking on a button I would like it to toggle between maximized / minimized states. My top level app component has a boolean state field (maximizedInfo
in the example below) that tracks whether the information panel is maximized or not and accordingly renders either just the panel or the full grid of my application with many other DOM elements. The below code is obviously a minified example but the main idea is that the render()
method of my top-level component generates two very different DOM trees depending on the state. Unfortunately, I have discovered that my information panel component keeps getting unmounted and the constructor is called on every state change, thus losing the state the information panel component had accumulated.
What is the proper way to address that and implement this sort of functionality in React?
const React = require('react');
class InformationPanel extends React.Component {
constructor(props) {
console.log('InformationPanel:: constructor'); // this keeps getting called
super(props);
}
render() {
return (
<div>
<a id='information' class='nav-link' href="#" onClick={this.props.toggleInfoPanel}>toggle</a>
short info
</div>
);
}
}
class App extends React.Component {
constructor(props) {
super(props);
this.state = {
maximizedInfo: false
};
this.toggleInfoPanel = this.toggleInfoPanel.bind(this);
}
toggleInfoPanel() {
this.setState({maximizedInfo: !this.state.maximizedInfo});
}
render() {
if (this.state.maximizedInfo)
return (
<div class='container-fluid'>
<div class='row no-gutters'>
<div class='col-12 padding-0'>
<InformationPanel toggleInfoPanel={this.toggleInfoPanel}/>
</div>
</div>
</div>
)
else return (
<div class='container-fluid'>
<div class='row no-gutters'>
<div class='col-10'>
some other info that takes up more space ...
</div>
<div class='col-2 padding-0'>
<InformationPanel toggleInfoPanel={this.toggleInfoPanel}/>
</div>
</div>
</div>
);
}
}