Code
Documentation and examples for the Code component.
When To Use
When you want to display source code with syntax highlighting, such as in tutorials or documentation.
Example Usage
javascript
console.log('Hello World'); astro
<Code code="console.log('Hello World');" language='javascript' /> Show Line Numbers
You can enable line numbers by passing `showLineNumbers={true}`.
greet.js
function greet(name) {
console.log(`Hello, ${name}!`);
}
greet('World'); astro
<Code
code={`function greet(name) {
console.log(\`Hello, \${name}!\`);
}
greet('World');`}
language='javascript'
showLineNumbers={true}
filename='greet.js'
/> Hide Header and Copy Button
You can disable the copy button using `copyButton={false}` and hide the header completely with `showHeader={false}`.
git clone https://github.com/example/repo.git
cd repo
npm install astro
<Code
code={`git clone https://github.com/example/repo.git
cd repo
npm install`}
language='bash'
copyButton={false}
showHeader={false}
/> How to Use
To use the Code component, import it from its location and pass the required props.
astro
import Code from '@/components/data-display/Code.astro';
<Code
code="console.log('Hello World');"
language="javascript"
showLineNumbers={true}
filename="example.js"
/> API Reference
| Property | Description | Type | Default |
|---|---|---|---|
| code | The source code to display. | string | - |
| language | The language of the source code for syntax highlighting. | string | 'javascript' |
| filename | The name of the file to display in the header. | string | - |
| showLineNumbers | Whether to show line numbers. | boolean | false |
| copyButton | Whether to show the copy button. | boolean | true |
| showHeader | Whether to show the header containing the filename/language and copy button. | boolean | true |
| class | Additional CSS classes to apply to the container. | string | - |