Building a Theme Switcher in React

Sedang Trending 1 bulan yang lalu

Composing Themes: Building Composable Theme Switchers successful React

Nitsan Cohen

Bits and Pieces

This guideline expands connected our earlier discussions astir creating composable themes for React components, focusing connected creation tokens, taxable providers, and discourse for customizable styling.

The theme-switcher constituent hosted successful nan scope connected bit.cloud

Here, we’ll study to build a composable theme switcher, enabling you to negociate taxable limitations and effortlessly override existing taxable tokens. This method not only improves accessibility and personalization but besides simplifies your theming process.

You tin spot the deployed app here.

In our past guide, we created a composable taxable component and extended it pinch a dark taxable component.

We’ll get started by initializing a caller workspace for our Bit components (replace my-sccount.my-scope pinch your ain bit.cloud relationship and scope name):

bit caller basal --default-scope my-account.my-scope

Next, to proceed from wherever we near disconnected successful nan erstwhile blog, we’ll fork (copy) the app from nan erstwhile example:

bit fork learnbit-react.theming/my-app

The themes are already installed arsenic limitations successful this app. Since we won’t modify them successful this guide, there’s nary request to import aliases fork nan taxable components directly.

First, create a React constituent utilizing Bit’s template for React components:

bit create respond themes/theme-switcher

We will usage nan headless theme-switcher component, which exposes an API to create your ain theme-switcher easily. Install it successful your workspace:

bit instal @teambit/base-react.themes.theme-switcher

We’ll instrumentality nan switcher arsenic follows:

// theme-switcher.tsx

import { MyThemeProps, MyTheme } from '@learnbit-react/theming.themes.my-theme';
import { MyDarkTheme } from '@learnbit-react/theming.themes.my-dark-theme';

import {
ThemeSwitcher arsenic ThemeSwitcherBase,
ThemeSwitcherProps arsenic BaseProps,
} from '@teambit/base-react.themes.theme-switcher';

// create an array of nan themes being composed
export const LightAndDarkThemes = [MyTheme, MyDarkTheme];

export type ThemeSwitcherProps = Omit<BaseProps<MyThemeProps>, 'themes'> & {
themes?: BaseProps<MyThemeProps>['themes'];
};

export usability ThemeSwitcher({
themes = LightAndDarkThemes,
...props
}: ThemeSwitcherProps) {
return <ThemeSwitcherBase themes={themes} {...props} />;
}

The dependency chart of nan recently created taxable switcher.

Here, we harvester nan ray and acheronian themes and walk them to nan guidelines taxable switcher component, which will grip nan switching for us.

The taxable switcher constituent we are creating besides exposes a toggle button. This is its implementation:

// theme-toggle-button.tsx

import React from 'react';
import { useNextTheme } from '@teambit/base-react.themes.theme-switcher';

export type ThemeTogglerProps = {} & React.HTMLAttributes<HTMLDivElement>;

export usability ThemeToggleButton({
className,
children,
...rest
}: ThemeTogglerProps) {

// usage this hooks exposed from nan guidelines taxable switcher constituent to toggle
const setNextTheme = useNextTheme();

return (
<div
role="button"
className={className}
onClick={setNextTheme}
tabIndex={-5}
onKeyDown={setNextTheme}
{...rest}
>
{children || 'Switch theme'}
</div>
);
}

And export it from nan index.ts file:

// index.ts

export { ThemeSwitcher } from './theme-switcher.js';
export type { ThemeSwitcherProps } from './theme-switcher.js';

// exporting nan toggle fastener from scale let different constituent to usage it
export { ThemeToggleButton } from './theme-toggle-button.js';

A bully constituent is well-documented and tested, truthful retrieve to instrumentality these arsenic well. I will skip nan implementation specifications here, but you tin look astatine nan exported type of nan theme switcher I created.

In nan app created, we’ll import nan ThemeSwitcher and nan ThemeToggleButton:

// my-app.tsx

import { Routes, Route } from 'react-router-dom';
import {
ThemeSwitcher,
ThemeToggleButton,
} from '@learnbit-react/theming.themes.theme-switcher';

function ThemedComponent() {
return (
<div
style={{
color: 'var(--text-color)',
backgroundColor: 'var(--background-color)',
}}
>
<h1>Hello Themed World!</h1>
</div>
);
}

// nan taxable switcher wraps nan app and functions arsenic a discourse component.

export usability MyApp() {
return (
<ThemeSwitcher>
<Routes>
<Route
path="/"
element={
<>
<ThemeToggleButton
style={{
color: 'var(--text-color)',
backgroundColor: 'var(--background-color)',
}}
>
Switch theme
</ThemeToggleButton>
<ThemedComponent />
</>
}
/>
</Routes>
</ThemeSwitcher>
);
}

Now we tin click connected nan fastener to toggle betwixt nan themes:

Understanding Design Tokens Overriding

When you move themes, nan creation tokens for illustration backgroundColor, textColor, and others person nan aforesaid names crossed themes but different values. This intends components usage these tokens without needing immoderate changes for different themes. Switching themes automatically updates these values crossed your app, ensuring a seamless modulation and accordant exertion of nan caller theme's creation choices.

Now that we person each nan implementation specifications set, it’s clip to tag nan exertion and nan taxable switcher pinch a merchandise version. Run nan pursuing command:

bit tag -m "release taxable switcher"

And export nan components:

bit export

The components will beryllium built connected Ripple:

Congrats connected your caller composable taxable switcher!

Notice: The app is configured to deploy to Netlify utilizing nan Netlify deployer component. If you wish to deploy your app to Netlify switch nan credeintails pinch yours, different region this from app pipeline aliases adhd a deployer of your own.

In component-based package architecture, each alteration you make is incremental. For example, if we alteration nan guidelines theme, nan alteration will beryllium reflected and propagated to each of its limited components:

However, if we alteration an extended taxable - nan dark theme - for example, nan guidelines taxable constituent will not get a type bump, but each nan dependants of nan acheronian taxable will get one:

Building a taxable switcher successful React enhances your app’s UI flexibility, allowing for move taxable changes that bespeak instantly crossed nan exertion without needing component-level adjustments. This attack simplifies taxable management, promotes a much accessible and personalized personification experience, and showcases nan applicable benefits of composable themes successful a component-based architecture.

By leveraging creation tokens and cautiously managing dependencies, you guarantee your themes are easy to widen and maintain. This guideline has walked you done mounting up a taxable switcher, demonstrating really to negociate themes successful React applications effectively.