LoginSignup
1
2

htmxを触ってみた

Posted at

最近注目されている(特に海外で)htmxを触ってみました。

公式の引用ですが、htmxでは属性を使用して、HTML内にてAJAX, CSSトランジション, WebSocket, サーバー送信イベントを直接記述できるのでハイパーテキストのシンプルさと強力さを備えた最新のユーザーインターフェイスを構築できます。

確認モーダル

jsだとconfirm()に当たるものを属性で書いています。

<h2>確認</h2>
<button hx-delete="/account" hx-confirm="本当に削除しますか?">
  削除する
</button>

スクリーンショット 2024-02-09 11.44.53.png

GET

expressで簡単なサーバーを作りgetリクエストを送った例です。
hx-targegtで指定しているid="result"に対して結果が表示されます。またhx-indicatorにより待ち時間にLoading...と表示されるようになります。

<h2>GET</h2>
<button 
  hx-get="/hello"
  hx-target="#result"
  hx-indicator="#indicator"
>
Click
</button>

<span class="htmx-indicator" id="indicator">Loading...</span>
<h2 id="result">target</h2>

スクリーンショット 2024-02-09 11.44.05.png

POST

Clickを押すとユーザー一覧を取ってきます。
inputに値を入力して、submitすることでユーザーを追加することもできます。hx-swap="beforeend"により後ろに追加されていきます。

<h2>ユーザー一覧</h2>
<form
  hx-post="/users/create"
  hx-trigger="submit"
  hx-target="#users"
  hx-swap="beforeend"
>
<input type="text" name="name" id="name" required/>
<button type="submit">Add</button>
</form>
<button
  hx-get="/users"
  hx-target="#users"
  hx-indicator="#indicator2"
  hx-swap="beforeend"
>
  Click
</button>
<span class="htmx-indicator" id="indicator2">Loading...</span>
<ul id="users"></ul>

スクリーンショット 2024-02-09 11.43.21.png

まとめ

簡単な例でしたが、jsを全く書かずに色々できてちょっと感動しました。

参考

1
2
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
2