Reactivity

Declare state

logo of Alpine Alpine

<h1 x-data="{ name: 'John' }" x-text="name"></h1>

logo of Marko Marko

<let/name="John">
<h1>Hello ${name}</h1>

Update state

logo of Alpine Alpine

<h1 x-data="{ name: 'John' }" x-init="name = 'Jane'" x-text="name"></h1>

logo of Marko Marko

<let/name="John">
<script>name = "Jane"</script>
<h1>Hello ${name}</h1>

Computed state

logo of Alpine Alpine

<h1
  x-data="{
  count : 10,
  get doubleCount() { return this.count * 2 }
}"
  x-text="doubleCount"
></h1>

logo of Marko Marko

<let/count=10>
<const/doubleCount=count * 2>
<div>${doubleCount}</div>

Templating

Minimal template

logo of Alpine Alpine

<h1>Hello world</h1>

logo of Marko Marko

<h1>Hello world</h1>

Styling

logo of Alpine Alpine

<h1 class="title">I am red</h1>
<button style="font-size: 10rem">I am a button</button>

<style>
  .title {
    color: red;
  }
</style>

logo of Marko Marko

<h1.title>I am red</h1>
<button style={ "font-size": "10rem" }>I am a button</button>
<button class=scopedButton>I am a style-scoped button</button>

<style>
  .title {
    color: red;
  }
</style>
<style/{ scopedButton }>
  .scopedButton {
    font-size: 10rem;
  }
</style>

Loop

logo of Alpine Alpine

<ul x-data="{ colors: ['red', 'green', 'blue'] }">
  <template x-for="color in colors">
    <li x-text="color"></li>
  </template>
</ul>

logo of Marko Marko

<ul>
  <for|color| of=["red", "green", "blue"]>
    <li>${color}</li>
  </for>
</ul>

Event click

logo of Alpine Alpine

<div x-data="{ count: 0 }">
  <p>Counter: <span x-text="count"></span></p>
  <button x-on:click="count++">+1</button>
</div>

logo of Marko Marko

<let/count=0>
<p>Counter: ${count}</p>
<button onClick() { count++ }>+1</button>

Dom ref

logo of Alpine Alpine

<input x-init="$el.focus();" />

logo of Marko Marko

<input/inputElement>
<script>
  inputElement().focus();
</script>

Conditional

logo of Alpine Alpine

<div
  x-data="{
  TRAFFIC_LIGHTS: ['red', 'orange', 'green'],
  lightIndex: 0,
  get light() { return this.TRAFFIC_LIGHTS[this.lightIndex] },
  nextLight() {
    this.lightIndex = (this.lightIndex + 1) % this.TRAFFIC_LIGHTS.length;
  }
}"
>
  <button x-on:click="nextLight">Next light</button>
  <p>Light is: <span x-text="light"></span></p>
  <p>
    You must
    <span x-show="light === 'red'">STOP</span>
    <span x-show="light === 'orange'">SLOW DOWN</span>
    <span x-show="light === 'green'">GO</span>
  </p>
</div>

logo of Marko Marko

static const TRAFFIC_LIGHTS = ["red", "orange", "green"];
<let/lightIndex=0>
<const/light=TRAFFIC_LIGHTS[lightIndex]>

<button onClick() { lightIndex = (lightIndex + 1) % TRAFFIC_LIGHTS.length }>
  Next light
</button>
<p>Light is: ${light}</p>
<p>
  You must
  <if=light === "red">STOP</if>
  <else if=light === "orange">SLOW DOWN</else>
  <else>GO</else>
</p>

Lifecycle

On mount

logo of Alpine Alpine

<p
  x-data="{ pageTitle: '' }"
  x-init="$nextTick(() => { pageTitle = document.title })"
>
  Page title: <span x-text="pageTitle"></span>
</p>

logo of Marko Marko

<let/pageTitle="">
<script>pageTitle = document.title</script>
<p>Page title: ${pageTitle}</p>

On unmount

logo of Alpine Alpine

<p
  x-data="{
  time: new Date().toLocaleTimeString(),
  timer: null,
  init() { this.timer = setInterval(() => (this.time = new Date().toLocaleTimeString()), 1000) },
  destroy() { clearInterval(this.timer) }
}"
>
  Current time: <span x-text="time"></span>
</p>

logo of Marko Marko

<let/time=new Date()>
<script>
  const id = setInterval(() => time = new Date(), 1000);
  $signal.onabort = () => clearInterval(id)
</script>
<p>Current time: ${time.toLocaleTimeString()}</p>

Component composition

Props

logo of Alpine Alpine

<!--Alpine JS suggests using a server-side templating engine or another frontend framework in conjunction with Alpine to do this-->

<div
  x-data="{
  name: 'John',
  age: 20,
  favouriteColors: ['green', 'blue', 'red'],
  isAvailable: true
}"
>
  <p>My name is <span x-text="John"></span></p>
  <p>My age is <span x-text="age"></span></p>
  <p>
    My favourite colors are <span x-text="favouriteColors.join(', ')"></span>
  </p>
  <p>I am <span x-text="isAvailable ? 'available' : 'not available'"></span></p>
</div>

logo of Marko Marko

<UserProfile
  name="John"
  age=20
  favouriteColors=["green", "blue", "red"]
  isAvailable
/>

Emit to parent

logo of Alpine Alpine

<div
  x-data="{ isHappy: true }"
  x-on:yes="isHappy = true"
  x-on:no="isHappy = false"
>
  <p>Are you happy?</p>
  <div>
    <button x-on:click="$dispatch('yes')">YES</button>
    <button x-on:click="$dispatch('no')">NO</button>
  </div>
  <p style="font-size: 50px" x-text="isHappy ? '😀' : '😥'"></p>
</div>

logo of Marko Marko

<let/isHappy=true>
<p>Are you happy?</p>
<AnswerButton
  onYes() { isHappy = true }
  onNo() { isHappy = false }
/>
<p style={ "font-size": 50 }>${isHappy ? "😀" : "😥"}</p>

Slot

logo of Alpine Alpine

<!--Alpine JS suggests using a server-side templating engine or another frontend framework in conjunction with Alpine to do this-->

<button
  x-data
  x-text="'Click me!'"
  style="
    background: rgba(0, 0, 0, 0.4);
    color: #fff;
    padding: 10px 20px;
    font-size: 30px;
    border: 2px solid #fff;
    margin: 8px;
    transform: scale(0.9);
    box-shadow: 4px 4px rgba(0, 0, 0, 0.4);
    transition: transform 0.2s cubic-bezier(0.34, 1.65, 0.88, 0.925) 0s;
    outline: 0;
  "
>
  <span>No content found</span>
</button>

logo of Marko Marko

<FunnyButton>Click me!</FunnyButton>

Slot fallback

logo of Alpine Alpine

<!--Alpine JS suggests using a server-side templating engine or another frontend framework in conjunction with Alpine to do this-->

<button
  x-data
  style="
    background: rgba(0, 0, 0, 0.4);
    color: #fff;
    padding: 10px 20px;
    font-size: 30px;
    border: 2px solid #fff;
    margin: 8px;
    transform: scale(0.9);
    box-shadow: 4px 4px rgba(0, 0, 0, 0.4);
    transition: transform 0.2s cubic-bezier(0.34, 1.65, 0.88, 0.925) 0s;
    outline: 0;
  "
>
  <span>No content found</span>
</button>

<button
  x-data
  x-text="'I got content!'"
  style="
    background: rgba(0, 0, 0, 0.4);
    color: #fff;
    padding: 10px 20px;
    font-size: 30px;
    border: 2px solid #fff;
    margin: 8px;
    transform: scale(0.9);
    box-shadow: 4px 4px rgba(0, 0, 0, 0.4);
    transition: transform 0.2s cubic-bezier(0.34, 1.65, 0.88, 0.925) 0s;
    outline: 0;
  "
>
  <span>No content found</span>
</button>

logo of Marko Marko

<FunnyButton/>
<FunnyButton>I got content!</FunnyButton>

Context

logo of Alpine Alpine

Missing snippet Help us to improve Component Party logo

logo of Marko Marko

<let/user={
  id: 1,
  username: "unicorn42",
  email: "[email protected]",
}>
<const/updateUsername(newUsername) {
  user = { ...user, username: newUsername };
}>

<h1>Welcome back, ${user.username}</h1>
<context={ ...user, updateUsername }>
  <UserProfile />
</context>

Form input

Input text

logo of Alpine Alpine

<div x-data="{ text: 'Hello World' }">
  <p x-text="text"></p>
  <input x-model="text" />
</div>

logo of Marko Marko

<let/text="Hello world">
<p>${text}</p>
<input value:=text>

Checkbox

logo of Alpine Alpine

<div x-data="{ isAvailable: true }">
  <input id="is-available" x-model="isAvailable" type="checkbox" />
  <label for="is-available">Is available</label>
</div>

logo of Marko Marko

<input#is-available
  type="checkbox"
  checked:=input.isAvailable
>
<label for="is-available">Is available</label>

Radio

logo of Alpine Alpine

<div x-data="{ picked: 'red' }">
  <div>Picked: <span x-text="picked"></span></div>

  <input id="blue-pill" x-model="picked" type="radio" value="blue" />
  <label for="blue-pill">Blue pill</label>

  <input id="red-pill" x-model="picked" type="radio" value="red" />
  <label for="red-pill">Red pill</label>
</div>

logo of Marko Marko

<let/picked="red">

<div>Picked: ${picked}</div>
<input#blue-pill
  type="radio"
  value="blue"
  checkedValue:=picked
>
<label for="blue-pill">Blue pill</label>

<input#red-pill
  type="radio"
  value="red"
  checkedValue:=picked
>
<label for="red-pill">Red pill</label>

Select

logo of Alpine Alpine

<div
  x-data="{
  selectedColorId: 2,
  colors: [
    { id: 1, text: 'red' },
    { id: 2, text: 'blue' },
    { id: 3, text: 'green' },
    { id: 4, text: 'gray', isDisabled: true }
  ]
}"
>
  <select x-model.number="selectedColorId">
    <template x-for="color in colors" x-bind:key="color.id">
      <option
        x-text="color.text"
        x-bind:value="color.id"
        x-bind:disabled="!!color.isDisabled"
        x-bind:selected="color.id === selectedColorId"
      ></option>
    </template>
  </select>
</div>

logo of Marko Marko

static const colors = [
  { id: 1, text: "red" },
  { id: 2, text: "blue" },
  { id: 3, text: "green" },
  { id: 4, text: "gray", isDisabled: true },
];
<let/selectedColorId=2>

<select value:=selectedColorId>
  <for|{ id, isDisabled, text }| of=colors>
    <option value=id disabled=isDisabled>
      ${text}
    </option>
  </for>
</select>

Webapp features

Render app

logo of Alpine Alpine

<h1>Hello world</h1>

logo of Marko Marko

<!doctype html>
<html>
  <body>
    <div id="app"></div>
    <script type="module" src="./app.js"></script>
  </body>
</html>

Fetch data

logo of Alpine Alpine

<div
  x-data="
		function fetchUsers() {
			return {
				users: null,
				isLoading: false,
				error: null,
				async init() {
					this.isLoading = true;
					try {
						this.users = (await (await fetch('https://randomuser.me/api/?results=3')).json()).results;
					} catch (err) {
						this.users = [];
						this.error = err
					}
					this.isLoading = false;
				},
			};
		}
	"
>
  <template x-if="isLoading">
    <p>Loading...</p>
  </template>

  <template x-if="error">
    <p>Error fetching users</p>
  </template>
  <template x-if="!error">
    <ul>
      <template x-for="user in users">
        <li>
          <img
            :src="user.picture.thumbnail"
            :alt="`picture of ${user.name.first} ${user.name.last}`"
          />
          <p x-text="`${user.name.first} ${user.name.last}`"></p>
        </li>
      </template>
    </ul>
  </template>
</div>

logo of Marko Marko

<try>
  <await|{ results: users }|=fetch("https://randomuser.me/api/?results=3").then(res => res.json())>
    <ul>
      <for|{ picture, name }| of=users>
        <li>
          <img src=picture.thumbnail alt="user">
          <p>${name.first} ${name.last}</p>
        </li>
      </for>
    </ul>
  </await>
  <@placeholder>
    <p>Fetching users...</p>
  </@placeholder>
  <@catch|error|>
    <p>An error occurred while fetching users</p>
  </@catch>
</try>