packages/dev/s2-docs/src/routers-s2.mdx
import {Step, Counter} from './Step';
<Step> <Counter />Render a [Provider](Provider) at the root of your app to set the locale, page background, and color scheme, load Spectrum fonts, and integrate with your client side router. When using S2 together with other versions of Spectrum, ensure that the S2 provider is the inner-most provider.A router has two properties:
navigate – a function received from your router for performing a client side navigation programmatically.useHref (optional) – converts a router-specific href to a native HTML href, e.g. prepending a base path.<ExampleSwitcher type="router" examples={['React Router', 'TanStack Router']}>
// src/app.tsx
import {Provider} from '@react-spectrum/s2';
import {BrowserRouter, useNavigate, useHref, type NavigateOptions} from 'react-router';
/*- begin highlight -*/
// Configure the type of the `routerOptions` prop on all React Spectrum components.
declare module '@react-spectrum/s2' {
interface RouterConfig {
routerOptions: NavigateOptions
}
}
/*- end highlight -*/
function App() {
let navigate = useNavigate();
return (
/*- begin highlight -*/
<Provider background="base" router={{navigate, useHref}}>
<Routes>
<Route path="/" element={<HomePage />} />
</Routes>
</Provider>
);
}
// src/routes/__root.tsx
import {Provider} from '@react-spectrum/s2';
import {useRouter, type NavigateOptions, type ToOptions} from '@tanstack/react-router';
/*- begin highlight -*/
// Configure the type of the `href` and `routerOptions` props on all React Spectrum components.
declare module '@react-spectrum/s2' {
interface RouterConfig {
href: ToOptions,
routerOptions: Omit<NavigateOptions, keyof ToOptions>
}
}
/*- end highlight -*/
export const Route = createRootRoute({
component: () => {
let router = useRouter();
return (
/*- begin highlight -*/
<Provider
background="base"
router={{
navigate: (href, opts) => {
if (typeof href === "string") return;
return router.navigate({ ...href, ...opts });
},
useHref: (href) => {
if (typeof href === "string") return href;
return router.buildLocation(href).href;
}
}}>
</Provider>
);
}
});
// Apply S2 background to the <html> element
/*- begin highlight -*/
import '@react-spectrum/s2/page.css';
/*- end highlight -*/
function App() {
return (
<Provider router={}>
</Provider>
);
}
By default, this uses the base background layer. This can be customized by setting the data-background attribute on the <html> element. The data-color-scheme attribute can also be set to force light or dark mode.
<html data-background="layer-1">
</html>