Skip to content
Advertisement

Reusable Alpine.js components?

How do I use Alpine.js to create a reusable component and display it? E.g., maybe I want to define an generic Alpine.js button component that changes text and color from parameters, then have my Alpine.js navbar component use the button component to show a login button.

Can I do this in pure client-side code, without relying on a server templating out all of the button HTML everywhere the button component is used?

Advertisement

Answer

Alpine.js contributer @ryangjchandler remarks that reusable templates are out of scope for Alpine.js:

The proposed [Alpine.js version 3] x-component directive will NOT have anything to do with templating or the markup for your component. Instead it will provide a way of writing more immediately reusable data sets & functions, whilst reducing the amount of directives you need to define in your markup.

If you need re-usable templates, I would consider using a server-side template engine or a more monolithic front end framework such as Vue or React. (link)

and

The functionality you are looking for is far out of the scope of Alpine. It’s designed to work alongside your existing markup from the server or static files, not replace / component-ise your markup. (link)

User contributions licensed under: CC BY-SA
4 People found this is helpful
Advertisement