Unlock the Power of Custom React Components with Theme UI
What is Theme UI?
Theme UI is a revolutionary library that empowers developers to create bespoke, themeable user interfaces using constraint-based design concepts. With its extensive API, Theme UI offers unparalleled developer ergonomics, making it an ideal choice for building custom component libraries, design systems, web applications, Gatsby themes, and more.
Building a Custom Component Library with Theme UI and TypeScript
In this hands-on tutorial, we’ll explore the process of creating and publishing a custom React component library using Theme UI and TypeScript.
Project Setup
Create a new folder for your project and initialize a React project using the npm init command. Install React and TypeScript with the following command:
npm install react typescript --save-dev
Organize your project structure as follows:
- themecomponentui
- src
- components
- Button
- Input
- components
- src
Configuring TypeScript
Configure TypeScript by creating a tsconfig.json file and updating it with the following snippet:
{
"jsx": "react",
"skipLibCheck": true,
"module": "ESNext",
"declarationDir": "types",
"sourceMap": true,
"outDir": "dist",
"moduleResolution": "node",
"emitDeclarationOnly": true
}
Configuring Rollup
Install Rollup and its plugins using the following commands:
npm install rollup @rollup/plugin-node-resolve @rollup/plugin-typescript @rollup/plugin-commonjs @rollup-plugin-dts @types/rollup-plugin-peer-deps-external @rollup-plugin-terser --save-dev
Configure Rollup by creating a rollup.config.js file and specifying the path to the CommonJS files and ES modules in the package.json file.
Creating Custom Components
Install Theme UI and create your custom components using the sx prop. For this tutorial, we’ll create a Button component and an Input component.
Button Component
Create a Button.tsx file and add the following snippet:
/** @jsxImportSource theme-ui */
import React from 'eact';
import { MouseEventHandler } from 'eact';
interface ButtonProps {
color?: string;
onClick?: MouseEventHandler;
}
const Button: React.FC<ButtonProps> = ({ color, onClick, children }) => {
return (
<button
sx={{
backgroundColor: color,
padding: '10px 20px',
border: 'none',
borderRadius: '5px',
cursor: 'pointer',
}}
onClick={onClick}
>
{children}
</button>
);
};
export default Button;
Input Component
Create an Input.tsx file and add the following snippet:
/** @jsxImportSource theme-ui */
import React from 'eact';
interface InputProps {
value: string;
onChange?: (value: string) => void;
}
const Input: React.FC<InputProps> = ({ value, onChange }) => {
return (
<input
sx={{
// add input styles here
}}
value={value}
onChange={onChange}
/>
);
};
export default Input;
Publishing to npm
Publish your custom component library to npm by running the following command:
npm publish
You’ve successfully published a React custom component library to npm!