テーマ管理
現代のウェブサイトでは、ユーザーに良い影響を与えるダークテーマとライトテーマの機能が見られます。ユーザーは自分の好みに合わせてテーマを変更できます。
これを実現するために、スタイリングには tailwindcss も使用しています。
まず、ウェブサイトに tailwindcss をインストールする必要があります。Qwik プロジェクトに tailwind を追加するのは非常に簡単です。ターミナルでこのコマンドを実行するだけです。
npm run qwik add tailwind
tailwind.config.js
ファイルでダークモードを有効にする必要があります。次のようになるはずです。
module.exports = {
content: ["./src/**/*.{js,ts,jsx,tsx,mdx}"],
darkMode: "class",
theme: {},
plugins: [],
};
次に、root.tsx
ファイルの head タグにこのコードを追加する必要があります。
<script
dangerouslySetInnerHTML={`
(function() {
function setTheme(theme) {
document.documentElement.className = theme;
localStorage.setItem('theme', theme);
}
var theme = localStorage.getItem('theme');
console.log(theme);
if (theme) {
setTheme(theme);
} else {
setTheme('light');
}
})();
window.addEventListener('load', function() {
var themeSwitch = document.getElementById('hide-checkbox');
themeSwitch.checked = localStorage.getItem('theme') === 'light'? true: false;
}
);
`}
></script>
変数名 "hide-checkbox" は、任意の名前で変更できます。これは、HTML ファイルと同じである必要があります。
次に、任意のコンポーネントにテーマ切り替えコードを追加できます。
import { component$, useStylesScoped$ } from "@builder.io/qwik";
import styles from "./style.css?inline";
export const ThemeSwitch = component$(() => {
useStylesScoped$(styles);
return (
<div class="flex items-center gap-3">
<label class="switch">
<input
type="checkbox"
id="hide-checkbox"
onClick$={() => {
const theme = document.documentElement.className;
if (theme === "light") {
document.documentElement.className = "dark";
localStorage.setItem("theme", "dark");
} else {
document.documentElement.className = "light";
localStorage.setItem("theme", "light");
}
}}
/>
<span class="slider round"></span>
</label>
</div>
);
});
テーマスイッチのスタイリング。
.switch{
position: relative;
display: inline-block;
width: 50px;
height: 30px;
background-color: red;
border-radius: 100px;
cursor: pointer;
}
.switch input{
display: none;
}
.slider{
width: 50px;
height: 25px;
border-radius: 25px;
background-color: #ccc;
position: relative;
cursor: pointer;
transition: all .3s linear;
}
.slider:before{
content: "";
position: absolute;
width: 25px;
height: 25px;
background-size: cover;
border-radius: 50%;
background-color: #fff;
top: 15px;
left: 5px;
bottom: 0;
margin: auto;
transition: all .3s linear;
}
input:checked + .slider{
background-color: #2196F3;
}
input:checked + .slider:before{
left: 22px;
}
次に、コードを実行します。これで、ダークテーマとライトテーマの機能が利用できます。