I'm building a web app with Next.js and React.
I'd like to show breadcrumbs and/or "go back" links on a set of pages.
Now, the simplest thing to do would be to render the <BackButton url="/url/to/go/back/to"/>
component on the page where it will be displayed, but for visual/layout reasons, it needs to be rendered above that level, in Next's top-level _app.js
component instead.
What's the simplest way to pass URLs "up" to the top-level app to be used by the back button?
The ideal pattern seems to be a hook in each page like:
useGoBackButton("/url/to/go/back/to")
But I'm struggling to figure out how to pass arguments in this way.
React context and useState()
seems like one approach too, but it feels like overkill - the URL will never change unless the page itself changes, so making it stateful seems like unnecessary overhead? Ideally this would work in a server-rendered way too.
What am I missing?
At the moment I'm using a trick similar to this to pass data up to the Next.js _app
component, but because I need to write the line in the module scope - outside the page component function, I can't access props that I often need to generate the correct URL.
MyPage.goBackUrl = "/can/only/have/hardcoded/urls/:(
I've also tried window.history.back()
, but the results are too unpredictable. It's important to say exactly which URL we want to go back to.
When I've needed to do similar things in the past with Rails, I've used <%= yield :head %>
and <% content_for :head %>
methods, which was clean and simple.