Theming React Components: A Practical Guide

Sedang Trending 1 bulan yang lalu

How to create a composable and extensible taxable for your React apps

Nitsan Cohen

Bits and Pieces

Theming ensures consistency and coherence crossed your web application’s personification interface.

The scope contains nan components we will create successful this guide: learnbit.react/theming

By implementing a theme, developers tin support a accordant creation passim their React components, making it easier to negociate and update styles. This guideline will locomotion you done creating a unified taxable for React components, highlighting nan value of creation tokens, taxable providers, and discourse to execute a move and customizable styling approach.

A composable taxable supplier dependency graph

The first measurement is to create a workspace wherever we tin create, maintain, and export nan taxable component:

bit caller basal --default-scope your-org.your-scope

If you person already opened a scope connected bit.cloud, switch it pinch your-org.your-scope

Run nan pursuing to create a theme component:

bit create taxable themes/my-basic-theme

Here’s nan basal building of nan component:

In nan pursuing sections, we will study astir nan building of nan taxable constituent and really to constitute it successful your React apps.

Design tokens service arsenic nan instauration of a theming system. They are fundamentally variables that shop design-related values, specified arsenic colors, font sizes, and spacing. Begin by defining your creation tokens pinch sensible defaults. This ensures consistency crossed your exertion and simplifies nan theming process.

The creation tokens we usage are plain JavaScript objects. We leverage Typescript to person nan creation token afloat typed, which will thief america widen nan taxable provider, arsenic you’ll spot below.

// my-theme-tokens.ts

/**
* MyTheme tokens.
* Include each tokens successful this object.
*/
export const myThemeTokens = {
/**
* inheritance color. usage for superior surfaces crossed your design.
*/
backgroundColor: '#f5f5f5',

/**
* colour for wide intent matter color. expected to chiefly apply
* connected `backgroundColor`
*/
textColor: 'black',

/**
* superior marque color. utilized for superior telephone to actions.
* specified arsenic buttons, links, etc.
*/
primaryColor: 'black',

/**
* colour to usage for borders.
*/
borderColor: '#ededed',

/**
* colour for secondary surfaces connected nan surface specified
* arsenic cards aliases contented outlines.
*/
surfaceColor: '#ffffff',
};

// create a taxable type schema to let caller taxable to override
// aliases instrumentality a different taxable variety for illustration acheronian theme.
// successful lawsuit tokens are dynamically loaded from a json file, please state this adaptable an an interface.
export type MyThemeSchema = typeof myThemeTokens;

Notice really we export nan taxable schema. It will beryllium useful later erstwhile we want to widen nan taxable component.

The adjacent measurement involves creating a taxable provider. This supplier uses nan tokens you’ve defined to make a taxable object. Through a createTheme function, you tin toggle shape these tokens into a coherent theme, making it disposable passim your constituent tree.

// my-theme-provider.tsx

import { createTheme } from '@teambit/base-react.themes.theme-provider';
import { MyThemeSchema, myThemeTokens } from './my-theme-tokens.js';

/**
* creating and declaring nan my-theme theme.
* specify nan taxable schema arsenic a type adaptable for due type completions.
*/
export const MyThemeProvider = createTheme<MyThemeSchema>({
theme: myThemeTokens,
});

/**
* a respond hook for contextual entree to creation token
* from components.
*/
export const { useTheme } = MyThemeProvider;

The createThemefunction returns a ThemeProvider that makes each tokens disposable passim your app utilizing CSS variables. You tin besides entree nan values wrong JSX utilizing nan useTheme hook. Let’s spot really we taxable a constituent some ways.

The taxable supplier injects CSS properties into your application, enabling you to usage nan defined tokens arsenic CSS civilization properties. This method ensures that each components person entree to nan theme, allowing for accordant styling based connected nan defined tokens.

Let’s create a React app component:

bit create react-app my-app

We will render nan ThemedComponent and wrap it pinch MyTheme connected nan guidelines route:

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

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

export usability MyApp() {
return (
<Routes>
<Route
path="/"
element={
<MyTheme>
<ThemedComponent />
</MyTheme>
}
/>
</Routes>
);
}

We utilized an inline style to entree nan CSS variables, but you tin besides entree them from immoderate CSS/SCSS file.

Utilizing React Context pinch nan taxable supplier allows taxable styles to beryllium accessible crossed each components JSX. It is usually adjuvant erstwhile you want to render a style conditionally. Here’s a speedy example:

import { Routes, Route } from 'react-router-dom';
import { MyTheme, useTheme } from '@learnbit-react/theming.themes.my-theme';

function ThemedComponent() {
const taxable = useTheme();
return (
<div
style={{
color: 'var(--text-color)',
backgroundColor: 'var(--background-color)',
}}
>
<h1>Hello Themed World!</h1>
<p>The matter colour is {theme.textColor}</p>
</div>
);
}

export usability MyApp() {
return (
<Routes>
<Route
path="/"
element={
<MyTheme>
<ThemedComponent />
</MyTheme>
}
/>
</Routes>
);
}

And here’s really it looks:

In nan adjacent conception we will widen nan taxable and alteration nan inheritance color.

Customization and hold of nan taxable are straightforward. By leveraging nan instauration built pinch tokens and nan taxable provider, you tin easy present variations for illustration a acheronian mode aliases set nan taxable to fresh marque guidelines. This conception will guideline you done customizing and extending your taxable to accommodate various needs.

Let’s create a dark taxable constituent by forking nan existing one:

bit fork themes/my-theme themes/my-dark-theme

Now we tin alteration nan inheritance colour successful nan tokens file:

import { MyThemeSchema } from '@learnbit-react/theming.themes.my-theme';
/**
* MyTheme tokens for Dark Theme.
* Include each tokens successful this entity adapted for a acheronian theme.
*/
export const myDarkThemeTokens: MyThemeSchema = {
/**
* Background color. Use for superior surfaces crossed your design.
* Darker colour for acheronian theme.
*/
backgroundColor: '#121212',

/**
* Color for wide intent matter color. Expected to chiefly apply
* connected `backgroundColor`. Light colour for opposition against acheronian background.
*/
textColor: '#e0e0e0',

/**
* Primary marque color. Used for superior telephone to actions.
* Such arsenic buttons, links, etc. Can support it agleam for visibility.
*/
primaryColor: '#bb86fc',

/**
* Color to usage for borders. Lighter than inheritance but still dark.
*/
borderColor: '#373737',

/**
* Color for secondary surfaces connected nan surface such
* arsenic cards aliases contented outlines. Slightly lighter than nan background.
*/
surfaceColor: '#1e1e1e',
};

// Update nan taxable type schema to lucifer nan caller acheronian taxable tokens
export type MyDarkThemeSchema = typeof myDarkThemeTokens;

Now, adhd different way for nan caller taxable successful our app:

export usability MyApp() {
return (
<Routes>
<Route
path="/"
element={
<MyTheme>
<ThemedComponent />
</MyTheme>
}
/>
<Route
path="/dark"
element={
<MyDarkTheme>
<ThemedComponent />
</MyDarkTheme>
}
/>
</Routes>
);
}
The acheronian taxable route.

Obviously, you tin usage nan extended taxable successful different apps.

To merchandise nan components truthful they are disposable for depletion by others, we first person to tag them pinch a merchandise version.

bit tag -m "new taxable component"

And export it to bit.cloud:

bit export

The components are tested and built connected Ripple:

After nan build is successful, you tin usage aliases support nan components from immoderate workspace:

In this speedy journey, we’ve illustrated nan principle of component-based package engineering by creating a composable and reusable React taxable constituent utilizing Bit. This attack not only enhances codification reuse and streamlines improvement processes but besides underscores nan powerfulness of modular design. By constructing a taxable constituent that tin beryllium easy shared and integrated crossed projects, we embody nan principles of modern package engineering — promoting efficiency, scalability, and maintainability. Happy coding!