An Introduction to Qwik-Theme-Toggle Library: A Qwik Component for Theme Switching
Tags: qwik, typescript, webdev, productivity
Published: 2024-01-19 11:28:46

In the world of web development, user experience takes center stage. The Qwik-Theme-Toggle library, a lightweight and user-friendly Qwik component, allows users to switch between different visual themes, greatly improving the browsing experience. It integrates a theme toggle button into web applications and is compatible with Tailwind CSS and DaisyUI.

## What is Qwik-Theme-Toggle Library?
Qwik-Theme-Toggle is a powerful Qwik component developed as a JavaScript library. Its primary purpose is to introduce a theme toggle button in web applications. This button empowers users to smoothly switch between light, dark, and auto modes, thereby significantly improving their browsing experience. The library is designed to be lightweight and user-friendly, ensuring it doesn't impact the performance of your web application.

## Compatibility with Tailwind CSS and DaisyUI

A remarkable feature of the Qwik-Theme-Toggle library is its compatibility with [Tailwind CSS](https://tailwindcss.com/) and [DaisyUI](https://daisyui.com/), a plugin for Tailwind CSS. This compatibility allows the library to leverage the utility-first CSS framework's flexibility and a robust UI toolkit, facilitating the creation of visually appealing and responsive designs.

## Key Features of Qwik-Theme-Toggle Library

The Qwik-Theme-Toggle library offers several compelling features:

1. **Lightweight**: The library's lightweight design ensures it does not impact your application's loading speed.
2. **User-Friendly**: The theme toggle button is easy to locate and use, providing a smooth user experience.
3. **Versatile**: It supports three theme modes - light, dark, and auto. The auto mode adjusts the theme based on the user's system settings.
4. **Qwik Component**: As a Qwik component, it integrates seamlessly with applications built using Qwik.
5. **Compatibility**: The library is compatible with Tailwind CSS and DaisyUI, facilitating a utility-first approach and the use of a robust UI toolkit.

## Installation of Qwik-Theme-Toggle Library

You can install the Qwik-Theme-Toggle library using npm with the following command:

```bash
npm install qwik-theme-toggle
```

If you use Bun, the installation command is:

```bash
bun install qwik-theme-toggle
```

You can find more details about the package on its [npm page](https://www.npmjs.com/package/qwik-theme-toggle).

## Qwik-Theme-Toggle in Action

You can see the Qwik-Theme-Toggle library in action and experiment with it in this [CodeSandbox](https://codesandbox.io/p/github/lieranderl/qwik-theme-toggle/main).

You can also watch this short [example video](https://www.youtube.com/watch?v=51iWIiZFCQY) which demonstrates how to use the library in a web application.


## How to Use Qwik-Theme-Toggle Library

To utilize the Qwik-Theme-Toggle library, you need to make some additions to your `tailwind.config.js` file and your HTML file. 

The `tailwind.config.js` file is where you configure your project's Tailwind CSS settings. To use the Qwik-Theme-Toggle library with DaisyUI and Tailwind CSS, you need to make a few modifications to this file.

Here's how you should set up your `tailwind.config.js` file:

```javascript
module.exports = {
  content: [
    //...
    "./node_modules/qwik-theme-toggle/**/*.{cjs,mjs}"
  ],
  //..
  darkMode: "class", // for pure Tailwind CSS
  //...
  plugins: [require("daisyui")], // for DaisyUI
}
```

In the `content` array, you should include the path to the Qwik-Theme-Toggle library. This ensures Tailwind CSS applies its styling to the library.

The `darkMode` property should be set to `"class"` if you're using pure Tailwind CSS. This enables Tailwind's dark mode feature, which Qwik-Theme-Toggle utilizes to switch between light and dark themes.

Lastly, if you're using DaisyUI, you should add the DaisyUI plugin to the `plugins` array. This lets you use DaisyUI's data-theme attribute with the Qwik-Theme-Toggle library.


### Integrating the ThemeScript Component into Your HTML

To start managing the theme of your application right from the document's load, you need to integrate the `ThemeScript` component into the head section of your HTML file.

Here's how you can do it:

First, import the `ThemeScript` component from the `qwik-theme-toggle` library at the top of your file:

```html
//...
import { ThemeScript } from "qwik-theme-toggle";
//...
```

Then, include the `ThemeScript` component in the head section of your HTML file. You can customize the component by passing properties to it:

```html
<head>
  //...
  <ThemeScript
    themeStorageKey="theme" // name of the local storage theme key
    themeQuery="theme"      // (Optional) name of the query param to reflect theme
  />
</head>
```

In the example above, the `themeStorageKey` property is used to specify the name of the local storage theme key. The `themeQuery` property (optional) is used to specify the name of the query parameter to reflect the theme in the URL.


### Integrating the ThemeToggle Component into Your Code
To integrate the ThemeToggle component into your application import the ThemeToggle component from the qwik-theme-toggle library at the top of your file:
```html
//...
import { ThemeToggle } from "qwik-theme-toggle";
//...
```
Then, add the ThemeToggle component in your JSX code where you want the theme toggle button to appear. You can customize the component by passing props to it:
```html
<ThemeToggle
  themeStorageKey="theme"           // name of the local storage theme key
  themeQuery="theme"                // (Optional) name of the query param to reflect theme
  textSize="text-2xl"               // Size of the toggle button
  myClass={"hover:text-secondary"}  // Apply a custom class
/>
```
In the example above, the themeStorageKey and themeQuery props are used to synchronize the theme preference between local storage and the URL query parameter. The textSize prop sets the size of the toggle button, and the myClass prop allows you to apply a custom class to the button.


## Contribute and Explore the Qwik-Theme-Toggle Library
For those interested in contributing to the project or want to understand more about how the library works, you can access the source code on its [GitHub repository](https://github.com/lieranderl/qwik-theme-toggle).

The Qwik-Theme-Toggle library consists of three primary files:

1. **theme-script.tsx**: This TypeScript file handles the overall theme management. It contains the logic for setting the theme based on the user's selection or system settings, listening for changes to the preferred color scheme using a media query listener, and updating the theme accordingly. It also manages the synchronization of the theme preference between local storage and the URL query parameter. The `ThemeScript` component is used in the head section of your HTML file to start listening for theme changes as soon as the document is loaded.

2. **theme-toggle.tsx**: This TypeScript file handles the theme toggle functionality. It defines the `ThemeToggle` component which is responsible for managing the theme selection based on the user's choice. It includes the logic for the theme toggle switch and applies the selected theme to the document's root element. The `ThemeToggle` component is used in your application to listen for theme changes and apply the chosen theme.

3. **themeicon.css**: This CSS file provides the styles for the theme toggle button and the associated icons (sun for light mode, moon for dark mode, and a custom auto icon for auto mode). It defines classes for the toggle button and its child elements (sun, moon, auto), and includes a keyframes rule for a rotation animation that's applied to the active icon when the user switches between themes.

Together, these files enable the Qwik-Theme-Toggle library to provide a smooth and visually pleasing theme switching experience for your web application users.

## ThemeScript Functionality

The `ThemeScript` component is responsible for managing the theme selection based on user preference and system settings. Here's a quick overview of what the `ThemeScript` component is doing:

The `ThemeScript` component first defines the theme constants - LIGHT, DARK, and AUTO. It then has a `setTheme` function which applies the selected theme to the document's root element.

It listens for changes to the preferred color scheme using a media query listener and updates the theme accordingly. If the theme is set to AUTO, it will automatically switch between light and dark themes based on the user's system settings.

When the document is loaded, the `ThemeScript` component checks the local storage for any saved theme preference and applies that theme. It also syncs the theme preference between local storage and the URL query parameter(Optional).

The `ThemeScript` component is used in the head section of your HTML file to start listening for theme changes as soon as the document is loaded.

## ThemeToggle Functionality
The ThemeToggle component is responsible for managing the theme selection based on the user's choice. It handles the theme toggle logic and applies the selected theme to the document's root element. The ThemeToggle component is used in your application to listen for theme changes and apply the chosen theme.

Here's a brief overview of what the ThemeToggle component is doing:

- **setThemeTailwind**: This function applies the selected theme to the document's root element for Tailwind CSS.
- **setThemeDaisyUI**: This function applies the selected theme to the document's root element for DaisyUI.
- **setThemeQparams**: This function sets the theme in the URL query parameters.
- **handleThemeToggle$**: This function is executed when the theme toggle button is clicked. It handles the theme toggle logic based on the current theme mode and applies the chosen theme using the ApplyTheme function.
- **AutoIcon**: This component returns an SVG of the Auto Icon used in the theme toggle button.

## ThemeIcon.css Functionality
The ThemeIcon.css file provides the styling for the theme toggle button.

Here is what it does:

- .toggle-button: This class applies a smooth transition effect to the toggle button when it is clicked.
- .sun, .moon, .auto: These classes position the sun, moon, and auto icons absolutely within the toggle button. They are initially set to be transparent and transition to full opacity when active.
- @keyframes rotate: This keyframes rule defines a rotation animation that rotates the active icon from -45 degrees to 0 degrees.
- [icon-theme="dark"] .moon, [icon-theme="light"] .sun, [icon-theme="auto"] .auto: These selectors apply the rotation animation to the respective icon when the corresponding theme is active.
The CSS classes and animations provide a smooth and visually pleasing transition effect when the user switches between themes.

## Conclusion

The Qwik-Theme-Toggle library is a tool that can enhance the user experience of your web application by providing an efficient theme toggle feature. When used in conjunction with Tailwind CSS and DaisyUI, it enables developers to create visually appealing and personalized web applications. If you're developing a web application and want to provide your users with a smooth theme-switching experience, the Qwik-Theme-Toggle library is worth considering.