How to create a react components library with storybook?
Here are the steps to create a React components library with Storybook:
- Create a new project using the
create-react-app
command. This will create a new project with a basic React app, including all the necessary dependencies and scripts.
npx create-react-app my-components-library
- Install the
@storybook/react
package. This package contains the necessary tools to build and run a Storybook for your React components.
cd my-components-library
npm install --save @storybook/react
- Add a script to your
package.json
file to start the Storybook. This script will start the Storybook server and open it in your default web browser.
"scripts": {
"storybook": "start-storybook"
}
- Create a
src/components
directory and add your React components to it. Each component should be in its own file, and it should have a default export that exports the component.
// src/components/Button.js
import * as React from "react";
const Button = (props) => {
return <button>{props.children}</button>;
};
export default Button;
- Create a
.storybook
directory and add aconfig.js
file to it. This file will contain the configuration for your Storybook.
// .storybook/config.js
import { configure } from "@storybook/react";
function loadStories() {
require("../src/components/Button.js");
}
configure(loadStories, module);
- In the
loadStories
function, you can require all the components that you want to include in your Storybook. You can also create stories for each component, which are examples of how to use the component.
// .storybook/config.js
import { configure } from "@storybook/react";
import { storiesOf } from "@storybook/react";
import Button from "../src/components/Button";
function loadStories() {
storiesOf("Button", module)
.add("with text", () => <Button>Hello, world!</Button>)
.add("with emoji", () => (
<Button>
<span role="img" aria-label="so cool">
๐ ๐ ๐ ๐ฏ
</span>
</Button>
));
}
configure(loadStories, module);
- To run your Storybook, use the
npm run storybook
command. This will start the Storybook server and open it in your default web browser. You should see your components and stories in the Storybook UI.
npm run storybook
- To build your components library, run the
npm run build
command. This will create a production build of your library in thebuild
directory. You can then publish this build to a package registry, such as npm, and use it in other projects.
npm run build
By following these steps, you can create a React components library with Storybook, which allows you
ย
ย