5
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

もうclass:ディレクティブは古い?Svelte5時代におけるclass属性の使い方

5
Last updated at Posted at 2025-12-03

はじめに

Svelteは5.16以降、class属性にオブジェクトや配列を渡せるようになり、 従来よく使われていたclass:ディレクティブはあまり推奨されなくなっているので、知識をアップデートしていきましょう。

基本的なclass属性の使い方

他の属性と同じように、class属性にも動的なJavaScriptの式を埋め込めます。

文字列でのクラス指定

最もシンプルな方法は三項演算子などを使い、クラス名を文字列として切り替えるやり方です。

<div class={isLarge ? 'large' : 'small'}>
  動的なクラス
</div>

補足
class={undefined}class={null}の場合は属性が省略されますが、falseNaNなどのFalsy値は歴史的な経緯で文字列化されることがあります(class="false"など)。将来的にはFalsy値で属性が省略される方向に変わる見込みです。

オブジェクトや配列を使ったクラス制御

Svelte 5.16以降は、class属性にオブジェクトや配列を直接渡せるようになり、これまでより柔軟にクラスを管理できるようになりました。

オブジェクト形式で条件付きにクラスを切り替える

オブジェクトのキーをクラス名、値を真偽値として扱い、値がtruthyのキーだけがクラスに反映されます。

<script>
  let isCool = $state(true);
</script>

<div class={{ cool: isCool, lame: !isCool, active: true }}>
  isCoolがtrueなら `class="cool active"` になる
</div>

配列形式で複数のクラスをまとめて指定する

配列内のtruthyな値がクラスとして結合されます。複数の条件付きクラスをまとめたい場合やTailwind CSSのようなユーティリティクラスを使う際に便利です。

<script>
  let isFaded = $state(true);
  let isLarge = $state(false);
</script>

<div class={[
  'base-style',
  isFaded && 'saturate-0 opacity-50',
  isLarge && 'scale-200',
  'text-center'
]}>
  動的なクラスリスト
</div>
  • isFadedtrueなら"saturate-0 opacity-50"のクラスが適用される

コンポーネント間でクラスを組み合わせる

配列は他の配列やオブジェクトも含めるため、コンポーネントのclassPropsとして渡されたクラスをローカルクラスと組み合わせる用途にも適しています。

補足
Svelte 5.19 から、Svelte では要素のclass属性が受け入れる値の型であるClassValue型を公開しています。これは、コンポーネントのpropsに型安全なクラス名を使用したい場合に便利です

Button.svelte

<script lang="ts">
  import type { ClassValue } from 'svelte/elements';

  // Propsとしてclassを受け取る
  const props: { class: ClassValue } = $props();
</script>

<button class={['cool-button', props.class]}>
  ボタン
</button>

App.svelte

<script>
  import Button from './Button.svelte';
  let useTailwind = $state(false);
</script>

<Button 
  class={{ 'bg-blue-700 sm:w-1/2': useTailwind }}
>
 ボタン
</Button>

さいごに

Svelte 5.16からclass属性にオブジェクトや配列を使えるようになり、クラスの切り替えが簡単になりました。Tailwind CSSのようなユーティリティクラスライブラリとの相性がよくなったのでより便利に使えると思います。

5
0
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
5
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?