Spread multiple Alpine.data component factories into a single x-data directive to compose modular frontend state.
When a single UI element requires state from multiple Alpine components (e.g. dropdown state + search state), use spread syntax inside x-data to merge component factories.
<script>
document.addEventListener('alpine:init', () => {
Alpine.data('dropdown', () => ({ open: false, toggle() { this.open = !this.open } }));
Alpine.data('search', () => ({ query: '', clear() { this.query = '' } }));
});
</script>
<!-- Merge multiple data objects via spread operator -->
<div x-data="{ ...dropdown(), ...search() }">
<input x-model="query">
<button @click="toggle()">Toggle Menu</button>
</div>
- Composes multiple Alpine.data component factories into one container
- Keeps JavaScript state definitions modular and reusable
- Prevents deeply nested wrapper div structures in HTML markup
Related Tips
View all tips →Build Framework-Free Dropdowns with Tailwind and nextElementSibling
Create lightweight, zero-dependency toggle dropdowns using inline JavaScript nextElementSibling calls with Tailwind CSS hidden classes.
Smooth Cross-Document View Transitions with @view-transition and Shared Elements
Enable native cross-document page transitions and smooth shared element animations without JavaScript routing libraries using the CSS @view-transition at-rule and view-transition-name.