0

I'm currently struggling using React and its library react-router-dom.

To simplify:

I've this in my App component:

const App = () => {

  return (
    <Router>
      <Layout>
        <Switch>
           // <Other Routes />
          <Route path='/product/:id' component={ProductScreen} />
          // <Other Routes />
        </Switch>
      </Layout>
    </Router>
  )
}

The <ProductScreen /> (single product view) is wrapped like this: enter image description here

The <ProductNav /> component embeds two links from react-router-dom. It also includes the required logic to reach previous or next product. Like so for instance:

<Link 
   className='prev'
   to={`/product/${currentIndex - 1 < 0 ? ids[lastIndex] : ids[currentIndex - 1]}`}
>
   Previous
</Link>

It's working but I'm not satisfied with that approach because the <ProductScreen /> unmounts each time I click 'previous' or 'next' and this leads to some unaesthetic things on the page. I would like to prevent it from unmounting in order to have this instead:

enter image description here

I tried many things, read the doc but I'm quite stuck right now. If anyone has any idea of how to achieve that I would be glad to read it.

1 Answer 1

1

You can use Route nested Route as following:

<Header />
<Main>
<Route path="/products" component={Product> />
</Main>
<Footer />

on page Product

const {url} = useRouteMatch();
render() {
    <>
       <Navbar />
       <Route path=`${url}/:id` component={ProductDetail} />
    </>

}

Sign up to request clarification or add additional context in comments.

4 Comments

Thank you for your answer. I gave a try to your solution but this isn't working. When I click on prev or next, the <ProductScreen /> component still unmounts. I was expecting just to have the <ProductDetail /> to unmount...
I was doing it multiple times and it works. when you change id on /products/id, only component ProductDetail is reloaded.
did you log something on componentWillUnmount lifecycle?
In fact it seems working now... Don't know what I was messing up before. Thank you. For anyone having the same troubles I would recommend to check that link: reactrouter.com/web/example/nesting

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.