Authoring Examples
Code examples can be exported alongside source code to provide visual and interactive documentation of how your components, hooks, and utilities can be used.
Extension
Multiple examples can be exported using the examples
extension:
Button.tsx
Button.examples.tsx
Button.examples.tsx
import { Button } from './Button'
export function BasicUsage() {
return <Button label="Say hello" onAction={() => alert('Hello!')} />
}
export function DifferentSizes() {
return ['small', 'medium', 'large'].map((size) => (
<Button label="Say hello" size={size} />
))
}
Directory
Examples can be grouped into into a directory:
Button/
├── index.tsx
├── examples/
│ ├── 01.Basic.tsx
│ ├── 02.Advanced.tsx
Templating
Export a default component to enhance examples with additional behavior, rendering, or to provide a consistent layout for all examples in the file:
import { Button } from './Button'
import { Theme } from './Theme'
export default function Layout({ children }: { children: React.ReactNode }) {
return <Theme>{children}</Theme>
}
export function BasicUsage() {
return <Button label="Say hello" onAction={() => alert('Hello!')} />
}
export function DifferentSizes() {
return ['small', 'medium', 'large'].map((size) => (
<Button label="Say hello" size={size} />
))
}
This is also how MDX files work. The default export is used to control the
layout of the file.
Refer to the next section on rendering to learn how to use the data helper to render examples as routes.
Metadata
Metadata is auto-generated based on the example’s function name and its accompanying comment. Use export default
to provide additional metadata for the file:
import { Button } from './Button'
/** A collection of examples for the button component. */
export default function AllButtonExamples({
children,
}: {
children: React.ReactNode
}) {
return children
}
/** A basic example of using a button. */
export function BasicUsage() {
return <Button label="Say hello" onAction={() => alert('Hello!')} />
}
/** An example of using a button with different sizes. */
export function DifferentSizes() {
return ['small', 'medium', 'large'].map((size) => (
<Button label="Say hello" size={size} />
))
}