Reactivity

Declare state

logo of Alpine Alpine

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

logo of Ripple Ripple

import { track } from "ripple";

export default function Name() {
  let &[name] = track("John");

  return <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 Ripple Ripple

import { track } from "ripple";

export default function Name() {
  let &[name] = track("John");
  name = "Jane";

  return <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 Ripple Ripple

import { track } from "ripple";

export default function DoubleCount() {
  let &[count] = track(10);
  let &[doubleCount] = track(() => count * 2);

  return <div>{doubleCount}</div>;
}

Templating

Minimal template

logo of Alpine Alpine

<h1>Hello world</h1>

logo of Ripple Ripple

export default function HelloWorld() {
  return <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 Ripple Ripple

export default function CssStyle() {
  return <>
    <h1 class="title">"I am red"</h1>
    <button style={{ fontSize: "10rem" }}>"I am a button"</button>

    <style>
      .title {
        color: red;
      }
    </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 Ripple Ripple

export default function Colors() {
  const colors = ["red", "green", "blue"];

  return <ul>
    for (const color of colors; key color) {
      <li>{color}</li>
    }
  </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 Ripple Ripple

import { track } from "ripple";

export default function Counter() {
  let &[count] = track(0);

  function incrementCount() {
    count++;
  }

  return <>
    <p>"Count: "{count}</p>
    <button onClick={incrementCount}>"+1"</button>
  </>;
}

Dom ref

logo of Alpine Alpine

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

logo of Ripple Ripple

export default function InputFocused() {
  function autofocus(element) {
    element.focus();
  }

  return <input ref={autofocus} />;
}

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 Ripple Ripple

import { track } from "ripple";

const TRAFFIC_LIGHTS = ["red", "orange", "green"];

export default function TrafficLight() {
  let &[lightIndex] = track(0);

  let &[light] = track(() => TRAFFIC_LIGHTS[lightIndex]);

  function nextLight() {
    lightIndex = (lightIndex + 1) % TRAFFIC_LIGHTS.length;
  }

  return <>
    <button onClick={nextLight}>"Next light"</button>
    <p>"Light is "{light}</p>
    <p>
      "You must "
      if (light === "red") {
        <span>"STOP"</span>
      } else if (light === "orange") {
        <span>"SLOW DOWN"</span>
      } else if (light === "green") {
        <span>"GO"</span>
      }
    </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 Ripple Ripple

import { effect, track } from "ripple";

export default function PageTitle() {
  let &[pageTitle] = track("");

  effect(() => {
    pageTitle = document.title;
  });

  return <h1>"Page title: "{pageTitle}</h1>;
}

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 Ripple Ripple

import { effect, track } from "ripple";

export default function Time() {
  let &[time] = track(new Date().toLocaleTimeString());

  effect(() => {
    const timer = setInterval(() => {
      time = new Date().toLocaleTimeString();
    }, 1000);

    return () => clearInterval(timer);
  });

  return <h1>"Current time: "{time}</h1>;
}

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 Ripple Ripple

import { UserProfile } from "./UserProfile.tsrx";

export function App() {
  return <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 Ripple Ripple

import { track } from "ripple";

import { AnswerButton } from "./AnswerButton.tsrx";

export function App() {
  let &[isHappy] = track(true);

  function onAnswerNo() {
    isHappy = false;
  }

  function onAnswerYes() {
    isHappy = true;
  }

  return <>
    <p>"Are you happy?"</p>
    <AnswerButton onYes={onAnswerYes} onNo={onAnswerNo} />
    <p style={{ fontSize: "50px" }}>{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 Ripple Ripple

import { FunnyButton } from "./FunnyButton.tsrx";

export function App() {
  return <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 Ripple Ripple

import { FunnyButton } from "./FunnyButton.tsrx";

export function App() {
  return <>
    <FunnyButton />
    <FunnyButton>"I got content!"</FunnyButton>
  </>;
}

Context

logo of Alpine Alpine

Missing snippet Help us to improve Component Party logo

logo of Ripple Ripple

import { RippleObject } from "ripple";

import { UserContext } from "./UserContext.tsrx";
import { UserProfile } from "./UserProfile.tsrx";

export function App() {
  const user = new RippleObject({
    id: 1,
    username: "unicorn42",
    email: "[email protected]",
  });

  UserContext.set(user);

  return <>
    <h1>"Welcome back, "{user.username}</h1>
    <UserProfile />
  </>;
}

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 Ripple Ripple

import { bindValue, track } from "ripple";

export default function InputHello() {
  let &[text, textTracked] = track("Hello world");

  return <>
    <p>{text}</p>
    <input ref={bindValue(textTracked)} />
  </>;
}

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 Ripple Ripple

import { bindChecked, track } from "ripple";

export default function IsAvailable() {
  let &[isAvailable, isAvailableTracked] = track(false);

  return <>
    <input
      id="is-available"
      type="checkbox"
      ref={bindChecked(isAvailableTracked)}
    />
    <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 Ripple Ripple

import { bindGroup, track } from "ripple";

export default function PickPill() {
  let &[picked, pickedTracked] = track("red");

  return <>
    <div>"Picked: "{picked}</div>

    <input
      id="blue-pill"
      type="radio"
      value="blue"
      ref={bindGroup(pickedTracked)}
    />
    <label for="blue-pill">"Blue pill"</label>

    <input
      id="red-pill"
      type="radio"
      value="red"
      ref={bindGroup(pickedTracked)}
    />
    <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 Ripple Ripple

import { bindValue, track } from "ripple";

const colors = [
  { id: 1, text: "red" },
  { id: 2, text: "blue" },
  { id: 3, text: "green" },
  { id: 4, text: "gray", isDisabled: true },
];

export default function ColorSelect() {
  let &[selectedColorId, selectedColorIdTracked] = track(2);

  return <select ref={bindValue(selectedColorIdTracked)}>
    for (const color of colors; key color.id) {
      <option value={color.id} disabled={color.isDisabled}>
        {color.text}
      </option>
    }
  </select>;
}

Webapp features

Render app

logo of Alpine Alpine

<h1>Hello world</h1>

logo of Ripple Ripple

<!doctype html>
<html>
  <body>
    <div id="app"></div>
    <script type="module" src="./main.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 Ripple Ripple

import { useFetchUsers } from "./useFetchUsers.tsrx";

export function App() {
  const data = useFetchUsers();

  return <>
    if (data.isLoading) {
      <p>"Fetching users..."</p>
    } else if (data.error) {
      <p>"An error occurred while fetching users"</p>
    } else if (data.users) {
      <ul>
        for (const user of data.users; key user.login.uuid) {
          <li>
            <img src={user.picture.thumbnail} alt="user" />
            <p>{user.name.first}" "{user.name.last}</p>
          </li>
        }
      </ul>
    }
  </>;
}