5
3

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

Yamada UIでカラーモードを簡単に切り替える

Last updated at Posted at 2024-05-30

はじめに

気になっていたYamada UIを触っていて、カラーモードの切り替えが簡単にできるらしいので使ってみました。
今回の使用言語はReact×TypeScriptです。

使用例

まずはカラーモードを正常に動作させるために、vite.config.tsにプラグインを追加します。
※今回はViteプロジェクトを使用しています。

(Next.jsはこちら)

vite.config.ts
import { defineConfig, Plugin } from "vite";
import react from "@vitejs/plugin-react";
import env from "vite-plugin-env-compatible";
import { defaultConfig, getColorModeScript } from "@yamada-ui/react";

//プラグイン追加
function injectScript(): Plugin {
  return {
    name: "vite-plugin-inject-scripts",
    transformIndexHtml(html, ctx) {
      const content = getColorModeScript({
        initialColorMode: defaultConfig.initialColorMode,
      });

      return html.replace("<body>", `<body><script>${content}</script>`);
    },
  };
}

// https://vitejs.dev/config/
export default defineConfig({
  plugins: [
    react(),
    env({ prefix: "VITE", mountedPath: "process.env" }),
    injectScript(),
  ],
});

次に下記を参考にしてコンポーネントを呼び出します。こんなに簡単にできるとは!

tsx
 const { colorMode, toggleColorMode } = useColorMode();

  return (
    <>
          <Button onClick={toggleColorMode} mb={2}>
            {colorMode === "light" ? "ダーク" : "ライト"}モードに切り替える
          </Button>
    </>
  );

ライトモード使用時(例)
画面左上のボタンを押すとモードが切り替わります。

image.png

ダークモード使用時(例)

image.png

おわりに

他のUIコンポーネントライブラリではここまで簡単に実装できないのではないでしょうか。
公式ドキュメントも丁寧で見やすいのでぜひ覗いてみてください!

参考

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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?