URL based modal in react-router V4

五迷三道 提交于 2020-06-11 05:04:22

问题


I am trying to accomplish this modal:

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}/>

回答1:


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




回答2:


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>



回答3:


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>


来源:https://stackoverflow.com/questions/46267588/url-based-modal-in-react-router-v4

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!