Skip to content

Latest commit

 

History

History
80 lines (67 loc) · 2.1 KB

CodeBlock.mdx

File metadata and controls

80 lines (67 loc) · 2.1 KB
This component is automatically set up to override the `pre` element when using the [Next.js plugin](/packages/next).

Styling

The CodeBlock component can be styled using the className and style props to target specific descendant elements.

import { CodeBlock as MdxtsCodeBlock, Tokens } from 'mdxts/components'
import styles from './CodeBlock.module.css'

export function CodeBlock(props: React.ComponentProps<typeof MdxtsCodeBlock>) {
  return (
    <CodeBlock
      source="./counter/useCounter.ts"
      className={{
        container: styles.container,
        token: styles.token,
      }}
      style={{
        // Clear the default styles
        container: {
          boxShadow: undefined,
          borderRadius: undefined,
        },
      }}
    />
  )
}
Not every element can be styled using the `className` and `style` props. See the following section for fully customizing the `CodeBlock` component.

Overrides

If you need more customization, the CodeBlock component can be fully overridden by importing it from mdxts/components and extending it:

import { CodeBlock as MdxtsCodeBlock, Tokens } from 'mdxts/components'

export function CodeBlock(props: React.ComponentProps<typeof MdxtsCodeBlock>) {
  return (
    <MdxtsCodeBlock {...props}>
      <pre
        style={{
          whiteSpace: 'pre',
          wordWrap: 'break-word',
          overflow: 'auto',
        }}
      >
        <Tokens />
      </pre>
    </MdxtsCodeBlock>
  )
}
This will only render highlighted tokens. Use the other `CodeBlock` components like `LineNumbers` and `Toolbar` to render the other parts of the code block.

Now import the CodeBlock component in your mdx-components.tsx file and override the pre component to use it instead of the default CodeBlock component:

import { MDXComponents } from 'mdxts/components'
import { CodeBlock } from './CodeBlock'

export function useMDXComponents() {
  return {
    ...MDXComponents,
    pre: CodeBlock,
  } satisfies MDXComponents
}