I'm creating a header with multiple options and specific options will have class 'active' depending on the url pathname (e.g. 'plant/tree'). To do this I've set up component HeaderOptions and in state initialized boolean values for all options to false (no options are active on index). The logic I've implemented works when navigating to specific pathnames but when returning to index it gives me an infinite loop--I can't figure out a solution to this problem.
const Header = (props) => {
const {
location,
history,
} = props;
return (
<div className="Header">
<div className="grid-row">
<HeaderOptions location={location} history={history} />
</div>
</div>
);
};
const HeaderWithRouter = withRouter(Header);
class HeaderOptions extends React.Component {
state = {
treeOption: false,
prairieOption: false,
reportOption: false,
};
componentDidUpdate() {
const {
treeOption,
prairieOption,
reportOption,
} = this.state;
const {
location: {
pathname,
},
} = this.props;
if (pathname.includes('/plant/tree') && !treeOption) {
this.setOptionState('treeOption');
} else if (pathname.includes('/plant/prairie') && !prairieOption) {
this.setOptionState('prairieOption');
} else if (pathname.includes('/report') && !reportOption) {
this.setOptionState('reportOption');
} else if (pathname === '/') {
this.setOptionState(null);
}
}
setOptionState(optionName) {
const updateState = {
treeOption: false,
prairieOption: false,
reportOption: false,
};
if (optionName) {
updateState[optionName] = true;
}
this.setState(updateState);
}
...
componentDidUpdate(pathname: string) {
.....
} else if (pathname === "/" && (treeOption || prairieOption || reportOption)) {
this.setOptionState(null);
}
}