Script
Injects custom JavaScript into the preview iframe.
Script is an injection component that adds JavaScript to the preview iframe. It renders nothing in the React tree but injects a <script> tag into the iframe's document.
import { Script } from '@codespark/react';Basic Usage
Pass the Script component as a child of Codespark or CodesparkPreview:
import { , } from '@codespark/react';
const = `export default function App() {
return (
<button
className="px-4 py-2 bg-blue-500 text-white rounded"
onClick={() => window.sayHello()}
>
Click me
</button>
);
}`;
export default function () {
return (
< ={}>
<>{`window.sayHello = () => alert('Hello from injected script!')`}</>
</>
);
}Inline Scripts
Pass JavaScript code as children:
<>
{`
window.myGlobalFunction = () => {
console.log('Hello from global function');
};
`}
</>External Scripts
Load external scripts using the src attribute:
< ="https://cdn.example.com/library.js" />Props
Script accepts all standard HTML <script> attributes:
children
Inline JavaScript code to execute.
| Type | Default | Since |
|---|---|---|
string | - | v1.0.0 |
<>{`console.log('Hello')`}</>src
URL of an external script to load.
| Type | Default | Since |
|---|---|---|
string | - | v1.0.0 |
< ="https://example.com/script.js" />type
Script type (e.g., 'module', 'text/javascript').
| Type | Default | Since |
|---|---|---|
string | - | v1.0.0 |
< ="module">{`import { foo } from './bar.js'`}</>async
Whether to load the script asynchronously.
| Type | Default | Since |
|---|---|---|
boolean | - | v1.0.0 |
< ="https://example.com/script.js" />defer
Whether to defer script execution until the document is parsed.
| Type | Default | Since |
|---|---|---|
boolean | - | v1.0.0 |
< ="https://example.com/script.js" />Other Attributes
Any other valid <script> HTML attributes are also supported:
<
="https://example.com/script.js"
="anonymous"
="sha384-..."
/>Use Cases
Adding Global Functions
<>
<>
{`
window.formatDate = (date) => {
return new Date(date).toLocaleDateString();
};
`}
</>
</>Loading Third-Party Libraries
<>
< ="https://cdn.jsdelivr.net/npm/chart.js" />
</>Analytics or Tracking
<>
<>
{`
// Track preview interactions
document.addEventListener('click', (e) => {
console.log('Click tracked:', e.target);
});
`}
</>
</>Execution Order
Scripts are injected into the iframe's <head> element before the preview code runs. This ensures that global functions and libraries are available when your preview code executes.
Note
Inline scripts execute immediately. External scripts with async or defer may load after the preview renders.
Last updated on