-
This idea was raised in remix-run/react-router#8971 but I think it belongs in this repo. I'd like to be able to set className (or other attributes) dynamically for each page—by dynamically I mean that, when the route changes, the className for the body element should be fetched by a function I'd define. This function should take the full route path as a parameter and return a Promise with the class name to set (or, of course, a Promise with an object holding the HTML attributes to set). This function would work sort of like the |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment
-
If it's not async, in your root route component you can use If you need to do it async (e.g. fetch an API or query a DB) you will need to do it in the loader, you could either add let matches = useMatches()
let { className } = matches.map(match => match.data).reverse().first(data => data?.className) Something like that, grab the className returned by a loader, starting by the last matching route, so leaf routes takes precedence over their parent routes. |
Beta Was this translation helpful? Give feedback.
If it's not async, in your root route component you can use
useLocation().pathname
to know the current URL pathname and derive the className from that.If you need to do it async (e.g. fetch an API or query a DB) you will need to do it in the loader, you could either add
shouldRevalidate
to the root route and always returntrue
so it always runs again or you can return the className from any other loader and use useMatches to grab the data returned by any loader and pick somehow which value to use (e.g. always use the last route defining a className).Something like tha…