Alpine.magic()

Define custom magic properties (prefixed with $).

What is Alpine.magic()?

Alpine.magic() lets you create your own magic helpers that are accessible in any Alpine expression, just like built‑in magics such as $el or $store. They are prefixed with $.

When to Use

Use Alpine.magic() when you have a utility function that you want to use across many components without importing it each time – for example, a date formatter, a random number generator, or a custom logger.

Defining a Magic

Code
Alpine.magic('upper', () => str => str.toUpperCase())
// Usage: <span x-text="$upper('hello')"></span> <!-- HELLO -->

Accessing the Component

The factory function receives the current component's reactive data (if used inside an x-data context) as an argument. This allows you to create magics that interact with the component's state.

Code
Alpine.magic('echo', (component) => (key) => component[key])
// <span x-text="$echo('name')"></span>

💡 Tip

Magics are global, so be careful with naming conflicts. Always prefix your custom magics with a namespace, e.g., $myPlugin_log.

Helpful? Share this page!↑ Back to top