Script
The Script component allows you to write JavaScript code directly in your EDL templates.
Usage
<Script>
// Any JavaScript code here
const $message = "Hello from script!";
const $calculateTotal = (items) => {
return items.reduce((sum, item) => sum + item.price, 0);
};
</Script>
<Text>{$message}</Text>
<Text>Total: {$calculateTotal(items)}</Text>
Variable Scope
Variables defined in a Script component are available to all components in the template. To make a variable available globally, prefix it with $:
<Script>
// This variable is available globally
const $userName = "John";
// This variable is only available within this Script
const privateData = "password";
</Script>
<Text>Welcome, {$userName}</Text>
Dependencies
Use the :dependencies prop to re-run the script when values change:
<Script :dependencies={[data.products]}>
const $totalPrice = data.products.reduce((sum, product) => sum + product.price, 0);
const $formattedPrice = new Intl.NumberFormat('en-US', {
style: 'currency',
currency: 'USD'
}).format($totalPrice);
</Script>
<Text>Total: {$formattedPrice}</Text>
runBeforeMount
Use the runBeforeMount prop to execute the script before the component is mounted:
<Script runBeforeMount={true}>
// This code runs before the component mounts
const $initialData = fetchInitialData();
</Script>
Best Practices
- Keep Scripts Small: Break complex logic into multiple Script components
- Use Dependencies: Always specify dependencies for reactive scripts
- Prefix Global Variables: Always use
$prefix for global variables - Avoid Side Effects: Minimize direct DOM manipulation or timers
- Error Handling: Include try/catch blocks for robust error handling