Browser Entry
Access collections from browser/client environment.
Using the Macro API?
Macro collections can be imported on the client directly, without a client loader. See Macro API for the equivalent usage.
Usage
The generated outputs are optimized using async imports for browser environments.
Only doc/docs collections are accessible on browser.
import browserCollections from 'collections/browser';
// unloaded entries
console.log(browserCollections['collection name'].raw);
// define client-side collection loader
const clientLoader = browserCollections['collection name'].createClientLoader({
component(
// access the compiled file
{ default: MDX },
// define props (optional)
props: { myProp: string },
) {
return (
<div>
<MDX />
</div>
);
},
});
// server (static generator) return a path
async function serverLoader() {
return source.getPage(slugs)!.path;
}
async function loader() {
const path = await serverLoader();
// preload the path
await clientLoader.preload(path);
return { path };
}
function Page() {
const { path } = loader();
// render the content
return clientLoader.useContent(path, {
myProp: 'hello world',
});
}Examples
The examples below are for non-RSC usage on React Router and TanStack Start. On Next.js and Waku, prefer RSC with the server entry for better client performance.
The example apps in our repository use the Macro API for this instead. They are a good reference for a complete setup.
import type { Route } from './+types/docs';
import { source } from '@/lib/source';
import browserCollections from 'collections/browser';
export async function loader({ params }: Route.LoaderArgs) {
const slugs = params['*'].split('/').filter((v) => v.length > 0);
const page = source.getPage(slugs);
if (!page) throw new Response('Not found', { status: 404 });
return {
path: page.path,
};
}
const clientLoader = browserCollections.docs.createClientLoader({
component({ frontmatter, default: MDX }) {
return (
<div className="prose">
<h1>{frontmatter.title}</h1>
<MDX />
</div>
);
},
});
export default function Page(props: Route.ComponentProps) {
const { path } = props.loaderData;
return clientLoader.useContent(path);
}How is this guide?
Last updated on
