I'm trying to build a modal that behaves similar to the modal that it's used to display a specific tweet.
The react-router docs has got me covered with the first part, that is, loading a modal in the same screen.
Here's the react-router example in codesandbox
The problem is that I have no idea what to do to make it possible for a user to bookmark the url that it's created when the modal is display (in the example /gallery/img/1)
and then based on that url being able to load the page with the same component(the Gallery component) in the background and the modal open.
P.S. In the example in codesandbox, I intentionally left out some routes in the ModalSwitch component.
To use React Router without changing the URL, we can use the MemoryRouter component. to import the MemoryRouter component and then wrap it around App to let us navigate with React Router without changing URLs.
Using react-router-dom to Change URL Path and Render Components. The react-router-dom package is great for rendering different React components based on the url path. Therefore, React components can lead to others by changing the url path.
Use the Navigate element to set a default route with redirect in React Router, e.g. <Route path="/" element={<Navigate to="/dashboard" />} /> . The Navigate element changes the current location when it is rendered. Copied!
This is the power of React Router and its ability to render routes anywhere. The concept is that a Route takes a path. If that Route is rendered and the path is matched then the supplied React will render. Generally routes are thought of as full pages when in fact it could control a full page, or a small component.
When the modal route is visited directly, which is modal/1 in our example, then none of the checks are true. Now we can use this boolean value to both render the <Route/> outside of the <Switch/>, and to decide which location object to pass to location prop of <Switch/>.
Consequently, it’s quite common that React App Components get very deeply nested. We are talking dozens of levels deep, and often more. So if one of those deeply nested Components needs to show a modal, it’s going to face some serious CSS issues.
The Redirect component from React Router can be used to redirect the user to another path. You can also pass in other user information like name and user ID using props to the wrapped component.
Perhaps you could create two routes, gallery and gallery/img/:id, that point to the same gallery component. Then during componentWillMount of the gallery component you could check if the URL contains an id param and decide to render the modal and which image to load.
You could then bookmark the UR, possibly remove for the ModalSwitch component entirely and also allow for redirecting a user back to the gallery route when closing the modal, keeping the URL accurate at all times.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With