URL based modal in react-router V4

Viewed 13972

I am trying to accomplish this modal:

enter image description here

I want to render my image gallery, and when clicking on an image, the popup needs to be opened. I want to do it with urls and not with state/store changes. for example:

the link : "/gallery/popular/fhoeuwy3928" will render the gallery in the back and the popup in front.

In react-router 3 it was simple with nested routes. How can I do it with v4?

These are my current routes:

<Route exact path='/' component={Home}/>
<Route path='/gallery/:category' component={Gallery}/>
<Route path='/gallery/:category/:id' component={Popup}/>
3 Answers

There is a good example here, in React Router v4 docs https://reacttraining.com/react-router/web/example/modal-gallery

It well explained there, but anyway - the main thing there <Switch> component, if image opened in modal will keep location property the same, while we could open our modal "window" in case if it needed or we not outputing anything:

{isModal ? <Route path='/img/:id' component={Modal} /> : null}

P.S.

Decided to put an answer here, even though probably it's too late

Faced same problem lately, aimed to change from v2 to v4, spent couple hours, trying to solve it by myself (but, obviously, it was in the docs, silly me), hope this would be helpful

Overview

Using the react router modal example, here is a sandbox I put together.

How it works

What we wanted was to have a nested route, which could have a modal opened on it, and we wanted that modal to have a route. So, we solved this by having multiple paths for the "gallery" route - one for the gallery itself and the other for the modal.

Then, we'd just have an additional <Route> for the modal itself. This allows for deep-linking directly to the modal itself (while making sure the gallery loads in the background) and navigating to the modal from the gallery.

<div>
    <Switch location={background || location}>
        <Route exact path="/" children={<Home />} />
        {/* The key is to have multiple paths here */}
        <Route path={["/gallery", "/img/:id"]} children={<Gallery />} />
    </Switch>

    <Route path="/img/:id" children={<Modal />} />
</div>

Well, This is how I arranged the routes eventually:

MainView.js

 <Switch>
    <Route path='/gallery/:category' component={Gallery} /> 
 </Switch>

Gallery.js

  <Switch>
     <Route path={`${this.props.match.url}/:id`} component={Popup} />
  </Switch>
Related