I tried to implement Modal router as in the react router example but It works when used with Link
but it doesn't work when I try to use history.push
. I am trying to implement multilevel modal with programmatically navigating through. Check the stack-blitz
// This works
<Link
to={{
pathname: `/img/${id}`,
state: { background: location }
}}
>
<Thumbnail color={color} />
<p>{title}</p>
</Link>
// This doesn't
<a href="#" onClick={
() => history.push({
pathname: `/img/${id}`,
state: { background: location }
})
}>
<Thumbnail color={color} />
<p>{title}</p>
</div>
// My Router
<div>
<Switch location={background || location}>
<Route path="/" exact component={Home} />
<Route path="/contacts" exact component={Contacts} />
</Switch>
{background && <Route path="/contact/:name" children={<Modal />} />}
</div>
How do I fix this to work without Link
tag? What is the error in the code used?
I think this could be solved by adding event.preventDefault(). Because when you click on the link, whole page is reloaded and history.push() is never executed
<a href="#" onClick={
(e) => {
e.preventDefault()
history.push({
pathname: `/img/${id}`,
state: { background: location }
}})
}>