Component-Driven Development with Storybook in React
Utilizing Storybook to develop, test, and document React components in isolation.
0 likes
185 views
Rule Content
---
description: Enforce the use of Storybook for developing, testing, and documenting React components in isolation.
globs: src/components/**/*.tsx
tags: [React, Storybook, Component-Driven Development]
priority: 2
version: 1.0.0
---
# Component-Driven Development with Storybook in React
## Context
- Applicable to all React components within the project.
- Aims to enhance component modularity, reusability, and maintainability.
## Requirements
- **Storybook Integration**: Ensure Storybook is set up and configured to mirror the application's component structure.
- **Component Stories**:
- Create a dedicated `.stories.tsx` file for each React component.
- Include a default story showcasing the component with only its required props.
- Add additional stories to represent various states and interactions of the component.
- **Mock Data Usage**: Utilize mock data and handlers to simulate real-world scenarios within stories, avoiding reliance on external APIs.
- **Consistent Styling**: Apply global styles and theme providers within Storybook to ensure consistency with the main application.
- **Performance Optimization**: Implement dynamic story loading and pagination to maintain optimal performance as the number of stories grows.
## Examples
// Button.stories.tsx
import React from 'react';
import { ComponentMeta, ComponentStory } from '@storybook/react';
import Button from './Button';
export default {
title: 'Button',
component: Button,
argTypes: {
onClick: { action: 'clicked' },
},
parameters: {
docs: {
description: {
component: 'A simple button component',
},
},
},
} as ComponentMeta<typeof Button>;
const Template: ComponentStory<typeof Button> = (args) => <Button {...args} />;
export const Default = Template.bind({});
Default.args = {
label: 'Default Button',
};
export const Primary = Template.bind({});
Primary.args = {
label: 'Primary Button',
primary: true,
};
// .storybook/preview.tsx
import React from 'react';
import { ThemeProvider } from 'styled-components';
import { theme } from '../src/theme';
export const decorators = [
(Story) => (
<ThemeProvider theme={theme}>
<Story />
</ThemeProvider>
),
];