Create reusable components with Alpine JS reactivity ๐Ÿฆ‘

Overview

Apline JS Component

Create reusable HTML components sprinkled with Alpine JS reactive data ๐Ÿง

Example ๐Ÿ‘€

Page

We can render on page components by using a <template> tag with an id that matches the template attribute ๐ŸŽ‰

In this example we are using the person template to find the <template id="person"> element.

<div
  x-data="{
    people: [
      { name: 'John', age: '25', skills: ['JavaScript', 'CSS'] },
      { name: 'Jane', age: '30', skills: ['Laravel', 'MySQL', 'jQuery'] }
    ]
  }"
>
  <ul>
    <template x-for="person in people">
      <x-component-wrapper
        x-component
        template="person"
        x-data="{ item: person }"
      ></x-component-wrapper>
    </template>
  </ul>
</div>

<template id="person">
  <li class="user-card">
    <h2 x-text="item.name"></h2>

    <p x-text="item.age"></p>

    <ul>
      <template x-for="skill in item.skills">
        <li x-text="skill"></li>
      </template>
    </ul>
  </li>
</template>

Global

We can also render global components ๐ŸŒ

This works by passing a URL for an HTML file in the url attribute that matches to a HTML file within the app

In this example, we are telling Alpine JS to get the HTML from public/person.html ๐Ÿ•ต๏ธโ€โ™€๏ธ

<div
  x-data="{
    people: [
      { name: 'John', age: '25', skills: ['JavaScript', 'CSS'] },
      { name: 'Jane', age: '30', skills: ['Laravel', 'MySQL', 'jQuery'] }
    ]
  }"
>
  <ul>
    <template x-for="person in people">
      <x-component-wrapper
        x-component
        url="/public/person.html"
        x-data="{ item: person }"
      ></x-component-wrapper>
    </template>
  </ul>
</div>

Then in public/person.html we have this

<li class="user-card">
  <h2 x-text="item.name"></h2>

  <p x-text="item.age"></p>

  <ul>
    <template x-for="skill in item.skills">
      <li x-text="skill"></li>
    </template>
  </ul>
</li>

Install ๐ŸŒŸ

It's very easy to install Alpine JS plugins! ๐Ÿ™Œ

CDN

<script src="https://unpkg.com/[email protected]/dist/component.min.js"></script>
<script defer src="https://unpkg.com/[email protected]/dist/cdn.min.js"></script>

NPM/Yarn

npm i -D alpinejs-component

yarn add -D alpinejs-component

Then you can register the plugin.

import Alpine from "alpinejs";
import component from "alpinejs-component";

Alpine.plugin(component);

window.Alpine = Alpine;

Alpine.start();

Stats ๐Ÿ“Š

Here's some stats about the Alpine JS component package! As you can see, it's tiny ๐Ÿค

You might also like...

An application that has a frontend (user interface) that allows you to create, read, update or delete (CRUD) products using an API in which you can also create, read, update or delete products.

An application that has a frontend (user interface) that allows you to create, read, update or delete (CRUD) products using an API in which you can also create, read, update or delete products.

CRUD app with React and Firebase 9 An application that has a frontend (user interface) that allows you to create, read, update or delete (CRUD) produc

Sep 28, 2021

๐Ÿ““ The UI component explorer. Develop, document, & test React, Vue, Angular, Web Components, Ember, Svelte & more!

๐Ÿ““ The UI component explorer. Develop, document, & test React, Vue, Angular, Web Components, Ember, Svelte & more!

Build bulletproof UI components faster Storybook is a development environment for UI components. It allows you to browse a component library, view the

Jan 4, 2023

React components for efficiently rendering large lists and tabular data

React components for efficiently rendering large lists and tabular data

React components for efficiently rendering large lists and tabular data. Check out the demo for some examples. Sponsors The following wonderful compan

Jan 7, 2023

Bootstrap components built with React

React-Bootstrap Bootstrap 4 components built with React. Docs See the documentation with live editable examples and API documentation. To find the doc

Jan 5, 2023

โšก๏ธ Simple, Modular & Accessible UI Components for your React Applications

โšก๏ธ Simple, Modular & Accessible UI Components for your React Applications

Build Accessible React Apps with Speed โšก๏ธ Chakra UI provides a set of accessible, reusable, and composable React components that make it super easy to

Jan 4, 2023

:hourglass_flowing_sand: A higher order component for loading components with promises.

:hourglass_flowing_sand: A higher order component for loading components with promises.

A higher order component for loading components with dynamic imports. Install yarn add react-loadable Example import Loadable from 'react-loadable'; i

Jan 3, 2023

๐Ÿฏ visx | visualization components

๐Ÿฏ visx | visualization components

visx visx is a collection of reusable low-level visualization components. visx combines the power of d3 to generate your visualization with the benefi

Jan 4, 2023

Tweak React components in real time. (Deprecated: use Fast Refresh instead.)

React Hot Loader Tweak React components in real time โš›๏ธ โšก๏ธ Watch Dan Abramov's talk on Hot Reloading with Time Travel. Moving towards next step React-

Jan 1, 2023

React components for efficiently rendering large lists and tabular data

React components for efficiently rendering large lists and tabular data

react-window React components for efficiently rendering large lists and tabular data React window works by only rendering part of a large data set (ju

Jan 4, 2023
Comments
  • [QUESTION] Reactivity with X-MODEL

    [QUESTION] Reactivity with X-MODEL

    Hi!

    Thanks for this plugin, this gets me so-close to client-side templating without any frameworks or libraries like Vue or React.

    However, this might have to do with my setup, but it appears that this won't work fine with x-model directive. Here's what I'm trying:

    My HTML file includes:

    <html
      x-data = "alpine">
      <body>
        <x-component-wrapper
          x-component
          url = "/components/input/">
        </x-component-wrapper>
      </body>
    </html>
    

    My template file has the following:

    <div>
      <link
        href = "/css/bundle.css"
        rel = "stylesheet"/>
      <input
        x-model = "input"/>
    </div>
    

    I've my Alpine data model in my JavaScript bundle:

    import Alpine from 'alpinejs'
    import Component from 'alpinejs-component'
    Alpine.data('alpine', () => ({
      input: null
    }))
    Alpine.plugin(Component)
    Alpine.start()
    

    Now, I'm not sure how to bind the x-model to the <input>. Directly using x-model = "input" in my component works, however I need to be able to change the x-model = "<value>" for each of my <input> element. Any guidance would be super helpful! Also, I hope this is possible with the plugin because this would make developer experience so much better for my website made with Hugo. Currently, I've to copy-paste my input element several times and it's getting difficult to manage as I need to update all of those for a single change.

    But if it's not possible, I totally understand. The plugin seems to be great at what it's doing and I appreciate the work that's put into this.

    opened by Hrishikesh-K 4
  • [QUESTION] How to Style?

    [QUESTION] How to Style?

    -->
    <head>
      <style>
        .dropdown-toggle {
          width: 100px;
          height: 100px;
          background-color: #f5f5f5;
        }
      </style>
    </head>
    
    <x-component-wrapper x-component template="dropdown" x-data="dropdown"></x-component-wrapper>
    <x-component-wrapper x-component template="dropdown" x-data="dropdown"></x-component-wrapper>
    
    <template id="dropdown">
      <div @click="close" class="dropdown-toggle">
        <button x-on:click="open">Open</button>
        <div x-show="show" x-text="content"></div>
      </div>
    </template>
    
    <script type="module">
      import { default as Alpine } from 'https://cdn.skypack.dev/alpinejs'
      import alpinejsComponent from 'https://cdn.skypack.dev/alpinejs-component'
      function dropdown() {
        return {
          show: false,
          open() {
            console.log('open')
            this.show = true
            console.log(this.show)
          },
          close(event) {
            const button = this.$el.querySelector('button')
            const target = event.target
            if (this.$el.contains(target) && !button.contains(target)) {
              this.show = false
            }
          },
          get isOpen() {
            return this.show === true
          },
          content: 'Default content',
          init() {
            console.log(this.$el.parentElement)
            console.log('dropdown --- init')
          },
        }
      }
      Alpine.data('dropdown', dropdown) // ๆณจๅ†Œๆ•ฐๆฎ
      Alpine.plugin(alpinejsComponent) // ๆณจๅ†Œ็ป„ไปถ
      Alpine.start() // ๅฏๅŠจ็ป„ไปถ
    </script>
    

    style does not work

    opened by jackchoumine 2
  • [BUG] Issue Building with Vite

    [BUG] Issue Building with Vite

    I have installed the plugin with a package manager and created a basic component :

    <div x-data="tabs">
      <link rel="stylesheet" href="/assets/classless.css">
      <nav>
        <ul>
          <img alt="app_logo"
           src="../assets/logo.svg" />
          <span style="font-size: 1.5em ">rlog</span>
          <template x-for="tab in tabs">
            <li x-text="tab"></li>
          </template>
          <img class="float-right" alt="RFC logo" src="../assets/Logo_RFC_Couleur_Blanc.png"  />
        </ul>
      </nav>
    </div>
    

    I use it inside my index.html

    <x-component-wrapper 
          x-component
          url="../components/Navbar.html"
    ></x-component-wrapper>
    

    When I use npm run dev (vite --host 0.0.0.0 --port 3000) it work fine but when I use npm run build (vite build) it break because the url "../components/Navbar.html" doesn't exist anymore.

    I try fixing that by adding the component to the static assets with assetsInclude: ['/components/*.html'] in vite.config.js but it didn't work for several reasons :

    • A hash is added to the file name
    • The file is then stored in the assets folder, not 'components/'
    • The links inside are not process so there are broken

    Is there a way to fix that so I can steel use Vite to build?

    My vite.config.js

    import { resolve } from 'path'
    import { defineConfig } from 'vite'
    
    export default defineConfig({ 
      root : resolve(__dirname, 'app/'),
      build: {
        outDir : resolve(__dirname, 'dist/'),
        emptyOutDir: true,
      }
    })
    

    Thank you!

    bug 
    opened by TheBigRoomXXL 1
Owner
Mark Mead
Finding solutions with Vue, Shopify & Ruby on Rails.
Mark Mead
Reusable way to create smooth tab highlights.

useTabs Reusable way to create smooth tab highlights. Installation Install my-project with npm npm install @olivieralexander/usetabs Usage/Examples

OlivierAlexander 7 Jul 31, 2022
Create a performant distributed context state by synergyzing atomar context pieces and composing reusable state logic.

Synergies Create a performant distributed context state by synergyzing atomar context pieces and composing reusable state logic. synergies is a tiny (

Lukas Bach 8 Nov 8, 2022
A React utility belt for function components and higher-order components.

A Note from the Author (acdlite, Oct 25 2018): Hi! I created Recompose about three years ago. About a year after that, I joined the React team. Today,

Andrew Clark 14.8k Jan 4, 2023
we are make our components in story book. So if we add some components you can find document and example of useage in storybook.

we are make our components in story book. So if we add some components you can find document and example of useage in storybook.

๊ณ ์Šค๋ฝ 6 Aug 12, 2022
Providing accessible components with Web Components & Material You

tiny-material Still on developing, DO NOT use for production environment Run well on Google Chrome, Firefox, Chrome for Android, Microsoft Edge (Chrom

HugePancake 11 Dec 31, 2022
Nextjs-components: A collection of React components

nextjs-components A collection of React components, transcribed from https://vercel.com/design. 1 Motivation Blog post from 01/09/2022 Todo's Unit tes

null 94 Nov 30, 2022
Mobile app development framework and SDK using HTML5 and JavaScript. Create beautiful and performant cross-platform mobile apps. Based on Web Components, and provides bindings for Angular 1, 2, React and Vue.js.

Onsen UI - Cross-Platform Hybrid App and PWA Framework Onsen UI is an open source framework that makes it easy to create native-feeling Progressive We

null 8.7k Jan 8, 2023
This command line helps you create components, pages and even redux implementation for your react project

react-help-create This command line helps you create components, pages and even redux implementation for your react project. How to install it? To ins

Omar 27 Dec 10, 2022
A highly impartial suite of React components that can be assembled by the consumer to create a carousel with almost no limits on DOM structure or CSS styles.

A highly impartial suite of React components that can be assembled by the consumer to create a carousel with almost no limits on DOM structure or CSS styles. If you're tired of fighting some other developer's CSS and DOM structure, this carousel is for you.

Vladimir Bezrukov 1 Dec 24, 2021
TryShape is an open-source platform to create shapes of your choice using a simple, easy-to-use interface. You can create banners, circles, polygonal shapes, export them as SVG, PNG, and even as CSS.

Create, Export, Share, and Use any Shapes of your choice. View Demo ยท Report Bug ยท Request Feature ?? Introducing TryShape TryShape is an opensource p

TryShape 148 Dec 26, 2022