Welcome back to TWIL, our weekly series that serves as a platform for the Cuttlesoft team to share intriguing insights from the world of software development. In this week's post, Marisa navigates the complexities of Routing with PopoutForms in a React application, demonstrating how to manage component visibility and URL parameters for a seamless user interface. Dive into the world of Javascript and React as Marisa presents a case study from a recent application, illustrating how to dynamically handle data pull with unique URLs and enhance user navigation through browser history manipulation.
Routing with PopoutForms
Background
Similar to Modals, we use PopoutForms to display components on top of a mounted container. Visibility of a PopoutForm is controlled by props showForm
and setShowForm
state controlled by the parent container.
Use Case
For an application I was working on - we wanted to display a PopoutForm that had it's own URL with parameters for entityType
and uid
. Allowing us to dynamically pull data without having to pass in these as props, and allowing the user to use basic back
capabilities (pressing back button in the browser). We also needed to be able to display a show profile, with nested Artist/Venue profiles and navigate to these as well.
Solution
Wrap our ArtistVenueShow
component in a PopoutForm with props:
<PopoutForm
showForm
setShowForm={() => history.goBack()}
>
Update our routes to dynamically set location
in our Switch
based on background
. Add a route for the ArtistVenueShow
component that is added based on background
. Set the Dashboard route to be exact
otherwise the profile will never be displayed.
export default function Routes() {
const location = useLocation()
const background = location.state && location.state.background
return (
<>
...
<Container>
<Switch location={background || location}>
...
<PrivateRoute exact path="/dashboard" component={Dashboard} />
...
</Switch>
{background && (
<PrivateRoute
path="/dashboard/:entityType/:uid"
component={ArtistVenueShow}
key={Date.now()}
/>
)}
</Container>
...
</>
)
}
When navigating from the Dashboard to a profile, set the background as the current location (/dashboard
). This will result in the Dashboard container still being mounted and displayed behind the profile.
history.push({
pathname: `/dashboard/shows/${show.uid}`,
state: { background: location },
})
For a more advanced post on the topic of routing with popouts in React, check out Marisa's blog post: Dynamic Layers with React and React-Router.
- Javascript
- React