This example shows how to embed MDX snippets that can be stored loosely and rendered on demand as a small part of a page. Unlike doc and blog pages that will be mostly MDX content, these smaller snippets might exist only in portions of a page: like a homepage where we're showing code.
By using const numbers = [1, 2, 3]
instead of client side syntax highlighting we can ensure the code is a lot better formatted and can utilize MDX components (think tabs) that we might use in the larger doc pages
a | b | c | d |
---|
import { Box, Container, Flex, Text } from '@chakra-ui/react';
import fs from 'fs';
import { getMDXComponent } from 'mdx-bundler/client';
import Head from 'next/head';
import { useEffect, useMemo } from 'react';
import { Button } from '~/components/button';
import { BaseLayout } from '~/components/layouts/base';
import { compileMDX, componentsForMDX } from '~/utils;';
/* const result = await bundleMDX({ source: exampleMDX }); const { code, frontmatter } = result; */
export default function Home({ code }: { code: string }, frontmatter) {
/* const { code, frontmatter } = parseMDX();
const Component = useMemo(() => getMDXComponent(code), [code]); */
const Component = useMemo(() => getMDXComponent(code), [code]);
return (
<BaseLayout>
<Container maxW={1000}>
<Head>
<title>Create Next App</title>
<link rel="icon" href="/favicon.ico" />
</Head>
<Flex gap={12}>
<Box flexBasis="50%">
<Component components={componentsForMDX} />
</Box>
<Box>
<Text>This content over here is just part of the TSX page</Text>
</Box>
</Flex>
</Container>
</BaseLayout>
);
}
export async function getStaticProps({ params }) {
const data = fs.readFileSync('./snippets/test.mdx', 'utf-8');
const { code, frontmatter } = await compileMDX(data);
return { props: { code, frontmatter } };
}
This content over here is just part of the TSX page