Code Block Component
This is an MDX Component that allows you to render code blocks with syntax highlighting and tabbed navigation in your Docusaurus project's markdown documents.
What does this MDX Component do?
The CodeBlocks
component is designed to parse and render code snippets within your markdown content. It supports the following features:
- Syntax Highlighting: The component automatically applies syntax highlighting to the code blocks based on the specified language.
- Tabbed Navigation: If multiple code blocks with different languages are present, the component generates a tabbed interface, allowing users to switch between the different code snippets.
- Language Context: You can optionally provide a context for each language, which will be displayed alongside the language name in the tab.
Copy the Code into Your Components Folder
import React from 'react';
import { Tabs, TabsContent, TabsList, TabsTrigger } from "./tabs";
const DevDocsCodeBlocks = (props) => {
const parseCodeSnippets = (children) => {
let triggers = [];
let contents = [];
React.Children.forEach(children, (child) => {
console.log("is dis the child", child)
if (React.isValidElement(child) && (child.type === 'pre' || child.props.mdxType === 'pre')) {
const className = child.props.className || child?.props?.children?.props?.className
console.log("dis the class name", className)
if (typeof className === 'string' && className.includes('-')) {
console.log("dis the class name", className)
const language = className.split('-')[1];
const [lang, context] = language.split('::');
triggers.push(
<TabsTrigger key={language} value={language}>
{`${lang} ${context || ''}`}
</TabsTrigger>
);
contents.push(
<TabsContent key={language} value={language}>
{child.props.children}
</TabsContent>
);
}
}
});
return { triggers, contents };
}
const { triggers, contents } = parseCodeSnippets(props.children);
return (
<div className="mt-[1em] text-sm">
<Tabs defaultValue={triggers.length > 0 ? triggers[0].props.value : ''}>
<TabsList>{triggers}</TabsList>
{contents}
</Tabs>
</div>
);
};
export { DevDocsCodeBlocks };
Npm Libraries and Install Instructions
This component does not require any external npm libraries. However, it does import the Tabs
, TabsContent
, TabsList
, and TabsTrigger
components from a local file (./tabs
). Make sure to include the corresponding tabs.jsx
file in your components folder as well.
Use Component in your Markdown file
To use the CodeBlocks
component in your Markdown file, wrap your code blocks with the <CodeBlocks>
and </CodeBlocks>
tags.
console.log('Hello, World!!');