The Code Block component improves readability of embedded code samples with syntax highlighting and automatic line numbering.
Multiple Code Blocks may displayed as a tabset with the CodeBlockTabList, CodeBlockTab, and CodeBlockTabPanel components. A common use case for this is providing a code sample in multiple languages.
To ensure the Code Block is accessible:
- Provide a descriptive label such as the current filename or step in a process to clarify the purpose of the Code Block.
- Enable long line wrapping whenever possible for a better reading experience.
- Use the correct heading level for the CodeBlockHeader
Use variant="single-line"
for one line Code Blocks. Single line Code Blocks should not have showLineNumbers={true}
.
Code Blocks have variant="multi-line"
by default. Multi line Code Blocks should have a CodeBlockHeader with a logical label for the Code Block, like the language or file name.
Note for the maxLines
property: Code Block uses line-clamp to limit the number of lines visible. When using line-clamp, browsers add an ellipsis to the contents of the Code Block to indicate that there is more to scroll to. When the code is copied with the copy button, the ellipsis isn't included.
Multiple Code Blocks may be displayed as a tabset with the CodeBlockTabList, CodeBlockTab, and CodeBlockTabPanel components. Provide a logical name for each CodeBlockTab, like the language or file name.
The Code Block Tabs components use the Tabs Primitive. For full details on the primitive and what props to provide it, follow the Tabs Primitive documentation.
To modify what text is copied when the copy button is clicked, use the copyTextFormatter
prop.