A common pattern on Facebook and other applications is to show pictures in a gallery, this gallery may be an interactive modal. However if the user visits the page from just a URL you might want to display the gallery outside of the modal. React Router makes this simpler by allowing you to pass in a state object when routing.
First off lets setup our routes, we'll have our base Home
route component. Then we'll also setup a Photo
component. This will render a div with a random image in it.
https://gist.github.com/d4270f3c289bf295b640e392b978c9b3
Now we need to setup our app routes and also be able to navigate between them. We have 2 links, and then 2 routes. Our /
route for Home
needs the exact
prop otherwise it will render even when we visit the /photo
route.
https://gist.github.com/68d1f2069241c23b4fb21779d26480ab
Rather than just passing in a simple string to Link
you can pass in an object. This will be accessible in the location
prop that is passed into the component rendered on our <Route>
.
We'll add in {modal: true}
because if the user clicks on it they are active in the application and so we know it's not a fresh visit from someone just visiting a URL.
https://gist.github.com/b39e0cda2e65bd70d28f0559ed9fb4e0
Now we need to adjust our Photo
route component to respond when we indicate we want a modal. We destructure location
from our props that are passed in. We default state
to an empty {}
because in the event that state isn't set it will just be undefined.
Then we grab our modal
value off of state.
https://gist.github.com/02fa8509f5f09649634c897017db512c
Now with our knowledge of whether or not we are going to render a modal
we can make adjustments. For example we add a modal
className
to our outer div. We also render a Close
button that is just a link to the home route which will render a different route, thus causing the modal to close.
https://gist.github.com/cda0c8fef7e939a0505386cbf0681a7a
Passing state is an effective method to change the experience for users as they flow through your application while altering the experience for users that visit your application from a direct URL. Both experiences should be relatively identical as to not confuse the user from visit to visit, but route state should be used to enhance the users experience.
https://codesandbox.io/s/github/browniefed/tmp/tree/reactRouterModalRoute/?module=%2Fsrc%2FApp.js