I have a settings modal with tabs that are links to paths. When you click on the background outside the modal it executes history.goBack. But if you have been clicking other settings tabs you won't go back to the previous page before the settings modal was opened instead you go back to the previous setting tab clicked.
I have tried hacking my way to a solution like counting how many tabs where clicked to then use history.go(-numberOfTabsClicked) but I want to know if there is any better way of doing this like not registering the settings tab links in the history stack.
Here is some of my code if that helps.
function SettingsTabs(props) {
const { path } = props.match;
return (
<div className={styles["settings-tabs"]}>
<h2>Settings</h2>
<Tab linkTo={`${path}?tab=profile`} name="Profile" />
<Tab linkTo={`${path}?tab=account`} name="Account" />
<Tab linkTo={`${path}?tab=themes`} name="Themes" />
</div>
);
}
function Tab(props) {
return (
<NavLink
to={props.linkTo}
activeClassName={styles["tab-active"]}
style={{ textDecoration: "none" }}
>
<div role="button" className={styles["tab"]}>
{props.children}
<span>{props.name}</span>
</div>
</NavLink>
);
}
This is the Modal the above components are wrapped in.
function Modal(props) {
const history = useHistory();
const { pathname } = useLocation();
history.scrollRestoration = "auto";
const path = props.match;
useEffect(() => {
window.scrollTo(0, 0);
return null;
}, [pathname]);
return (
<div>
<div
onClick={() => history.goBack()}
className={styles["modal-bg"]}
/>
{props.children}
<div
onClick={() => history.goBack()}
style={{top: props.top, marginLeft: props.marginLeft}}
className={styles["modal-close-btn"]}
>
<CloseButton />
</div>
</div>
);
}
Answering my question I know but I have found a simple solution of adding replace boolean to NavLink.
return (
<NavLink
to={props.linkTo}
replace
exact
style={{ textDecoration: "none" }}
>...
From https://reactrouter.com/web/api/Link/replace-bool - When true, clicking the link will replace the current entry in the history stack instead of adding a new one.
Such an easy fix, I feel stupid for missing that before.