К основному содержанию
скилл CX Codex

writing-react-native-storybook-stories — скилл для Claude Code

Помогает агенту писать и править истории React Native по формату CSF: args, argTypes, декораторы, параметры аддонов и портируемые истории для тестов.

Установить в Claude Code · Через Skills CLI (Vercel) Все способы и платформы ↓
npx skills add storybookjs/react-native --skill writing-react-native-storybook-stories -a claude-code
Открыть на GitHub

Что делает writing-react-native-storybook-stories

Скилл описывает, как автору историй работать с @storybook/react-native v10 и Component Story Format. Агент получает правила именования файлов (ComponentName.stories.tsx рядом с компонентом), структуру meta с satisfies Meta<typeof Component>, типизацию историй через StoryObj<typeof meta>. Есть готовые шаблоны: несколько историй с общими args, кастомный render, рендер с хуками через именованную функцию, моки колбэков через fn() из storybook/test.

Отдельные разделы — про контролы и argTypes. Селект, слайдер диапазона, выбор цвета, условный контрол через if: { arg: 'advanced' }. TypeScript-типы пропсов подхватываются автоматически: string идёт в text, boolean в boolean, union в select. Параметры аддонов задаются на уровне истории, компонента или глобально в preview.tsx; для RN есть свои — noSafeArea, storybookUIVisibility, hideFullScreenButton, layout.

Осторожно с noSafeArea: если его включить, safe area должен обрабатывать сам компонент, потому что Storybook перестаёт добавлять отступы. В исходнике советуют брать useSafeAreaInsets() и применять инсеты как paddingTop/paddingBottom на контейнере, а для скролла — через contentContainerStyle. Глобальные декораторы кладутся в .rnstorybook/preview.tsx.

Какие задачи решает

  • написать первый файл историй для React Native компонента
  • настроить селект и слайдер через argTypes
  • замокать колбэк onPress в истории кнопки
  • обернуть историю в провайдер или контейнер через decorators
  • включить тёмный фон в аддоне Backgrounds

Примеры запросов агенту

  • Напиши историю для компонента Button в файле Button.stories.tsx по CSF
  • Добавь в meta argTypes с селектом размеров и слайдером прозрачности
  • Оберни эту историю в декоратор с центрированием по вертикали

Как установить writing-react-native-storybook-stories

1Через Skills CLI (Vercel)

npx skills add storybookjs/react-native --skill writing-react-native-storybook-stories -a claude-code

2Вручную: положить файлы

~/.claude/skills/writing-react-native-storybook-stories/SKILL.md

Папка скилла целиком; для одного проекта — .claude/skills/writing-react-native-storybook-stories/

По шагам, с командами для каждой платформы: Как установить скилл в Claude Code: пять способов

Вопросы о writing-react-native-storybook-stories

Как установить writing-react-native-storybook-stories в Claude?

Выполните npx skills add storybookjs/react-native --skill writing-react-native-storybook-stories -a claude-code. Файл скилла окажется по пути ~/.claude/skills/writing-react-native-storybook-stories/SKILL.md.

Что делает этот скилл?

Даёт агенту правила написания историй React Native в формате CSF: структура meta, типы StoryObj, args, argTypes, декораторы, параметры аддонов и портируемые истории для тестов.

Что будет, если выставить параметр noSafeArea?

Storybook перестанет добавлять отступы под safe area, и компонент должен обрабатывать их сам. В исходнике советуют useSafeAreaInsets() с инсетами в paddingTop/paddingBottom контейнера.

Исходный текст

SKILL.md · MIT
---
name: writing-react-native-storybook-stories
description: Create and edit React Native Storybook stories using Component Story Format (CSF). Use when writing .stories.tsx files, adding stories to React Native components, configuring Storybook addons (controls, actions, backgrounds, notes), setting up argTypes, decorators, parameters, or working with portable stories for testing. Applies to any task involving @storybook/react-native story authoring.
---

# React Native Storybook Stories

Write stories for React Native components using `@storybook/react-native` v10 and Component Story Format (CSF).

## Quick Start

Minimal story file:

```tsx
import type { Meta, StoryObj } from '@storybook/react-native';
import { MyComponent } from './MyComponent';

const meta = {
  component: MyComponent,
} satisfies Meta<typeof MyComponent>;

export default meta;
type Story = StoryObj<typeof meta>;

export const Basic: Story = {
  args: {
    label: 'Hello',
  },
};
```

## File Conventions

- Name: `ComponentName.stories.tsx` colocated with the component
- Import `Meta` and `StoryObj` from `@storybook/react-native`
- Default export: `meta` object with `satisfies Meta<typeof Component>`
- Named exports: UpperCamelCase story names, typed as `StoryObj<typeof meta>`
- Use `args` for props, `argTypes` for control config, `parameters` for addon config
- Use `render` for custom render functions, `decorators` for wrappers

## Story Patterns

### Multiple stories with shared args

```tsx
export const Primary: Story = {
  args: { variant: 'primary', title: 'Click me' },
};

export const Secondary: Story = {
  args: { ...Primary.args, variant: 'secondary' },
};
```

### Custom render function

```tsx
export const WithScrollView: Story = {
  render: (args) => (
    <ScrollView>
      <MyComponent {...args} />
    </ScrollView>
  ),
};
```

### Render with hooks (must be a named function)

```tsx
export const Interactive: Story = {
  render: function InteractiveRender() {
    const [count, setCount] = useReducer((s) => s + 1, 0);
    return <Counter count={count} onPress={setCount} />;
  },
};
```

### Actions (mock callbacks)

```tsx
import { fn } from 'storybook/test';

const meta = {
  component: Button,
  args: { onPress: fn() },
} satisfies Meta<typeof Button>;
```

Or via argTypes:

```tsx
argTypes: { onPress: { action: 'pressed' } },
```

### Custom story name

```tsx
export const MyStory: Story = {
  storyName: 'Custom Display Name',
  args: { label: 'Hello' },
};
```

### Custom title / nesting

```tsx
const meta = {
  title: 'NestingExample/Message/Bubble',
  component: MyComponent,
} satisfies Meta<typeof MyComponent>;
```

## Controls & ArgTypes

For the full control type reference, see [references/controls.md](references/controls.md).

Common patterns:

```tsx
const meta = {
  component: MyComponent,
  argTypes: {
    // Select dropdown
    size: {
      options: ['small', 'medium', 'large'],
      control: { type: 'select' },
    },
    // Range slider
    opacity: {
      control: { type: 'range', min: 0, max: 1, step: 0.1 },
    },
    // Color picker
    color: { control: { type: 'color' } },
    // Conditional control (shows only when `advanced` arg is true)
    padding: { control: 'number', if: { arg: 'advanced' } },
  },
} satisfies Meta<typeof MyComponent>;
```

Auto-detection: TypeScript prop types are automatically mapped to controls (`string` -> text, `boolean` -> boolean, union types -> select, `number` -> number).

## Parameters

### Addon parameters

```tsx
parameters: {
  // Markdown docs in the Notes addon tab
  notes: `# MyComponent\nUsage: \`<MyComponent label="hi" />\``,
  // Background options for Backgrounds addon
  backgrounds: {
    default: 'dark',
    values: [
      { name: 'light', value: 'white' },
      { name: 'dark', value: '#333' },
    ],
  },
},
```

### RN-specific UI parameters

| Parameter               | Type                                         | Description                                                                                                                                                                                                                                                                                                                                                                      |
| ----------------------- | -------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `noSafeArea`            | `boolean`                                    | Remove top safe area padding. **When using this, the component itself must handle safe areas** since Storybook will no longer provide safe area padding. Prefer `useSafeAreaInsets()` over `SafeAreaView` — apply insets as `paddingTop`/`paddingBottom` on the container, and for scrollable content use `contentContainerStyle` padding instead of wrapping in `SafeAreaView`. |
| `storybookUIVisibility` | `'visible'` \| `'hidden'`                    | Initial UI visibility                                                                                                                                                                                                                                                                                                                                                            |
| `hideFullScreenButton`  | `boolean`                                    | Hide fullscreen toggle                                                                                                                                                                                                                                                                                                                                                           |
| `layout`                | `'padded'` \| `'centered'` \| `'fullscreen'` | Story container layout                                                                                                                                                                                                                                                                                                                                                           |

Parameters can be set at story, meta (component), or global (preview.tsx) level.

## Decorators

Wrap stories in providers, layouts, or context:

```tsx
const meta = {
  component: MyComponent,
  decorators: [
    (Story) => (
      <View style={{ alignItems: 'center', justifyContent: 'center', flex: 1 }}>
        <Story />
      </View>
    ),
  ],
} satisfies Meta<typeof MyComponent>;
```

Global decorators go in `.rnstorybook/preview.tsx`:

```tsx
import { withBackgrounds } from '@storybook/addon-ondevice-backgrounds';
import type { Preview } from '@storybook/react-native';

const preview: Preview = {
  decorators: [withBackgrounds],
  parameters: {
    actions: { argTypesRegex: '^on[A-Z].*' },
    controls: {
      matchers: {
        color: /(background|color)$/i,
        date: /Date$/,
      },
    },
    backgrounds: {
      default: 'plain',
      values: [
        { name: 'plain', value: 'white' },
        { name: 'dark', value: '#333' },
      ],
    },
  },
};

export default preview;
```

## Configuration

### .rnstorybook/main.ts

```ts
import type { StorybookConfig } from '@storybook/react-native';

const main: StorybookConfig = {
  stories: ['../components/**/*.stories.?(ts|tsx|js|jsx)'],
  deviceAddons: [
    '@storybook/addon-ondevice-controls',
    '@storybook/addon-ondevice-backgrounds',
    '@storybook/addon-ondevice-actions',
    '@storybook/addon-ondevice-notes',
  ],
  framework: '@storybook/react-native',
};

export default main;
```

Story globs also support the object form for multi-directory setups:

```ts
stories: [
  '../components/**/*.stories.?(ts|tsx|js|jsx)',
  { directory: '../other_components', files: '**/*.stories.?(ts|tsx|js|jsx)' },
],
```

## Portable Stories (Testing)

Reuse stories in Jest tests:

```tsx
import { render, screen } from '@testing-library/react-native';
import { composeStories } from '@storybook/react';
import * as stories from './Button.stories';

const { Primary, Secondary } = composeStories(stories);

test('renders primary button', () => {
  render(<Primary />);
  expect(screen.getByText('Click me')).toBeTruthy();
});

// Override args in tests
test('renders with custom props', () => {
  render(<Primary title="Custom" />);
  expect(screen.getByText('Custom')).toBeTruthy();
});
```

For single stories use `composeStory`:

```tsx
import { composeStory } from '@storybook/react';
import meta, { Primary } from './Button.stories';

const PrimaryStory = composeStory(Primary, meta);
```

Setup global annotations for tests in a Jest setup file:

```ts
// setup-portable-stories.ts
import { setProjectAnnotations } from '@storybook/react';
import * as previewAnnotations from '../.rnstorybook/preview';
setProjectAnnotations(previewAnnotations);
```

## Addons Summary

| Addon       | Package                                 | Purpose                    |
| ----------- | --------------------------------------- | -------------------------- |
| Controls    | `@storybook/addon-ondevice-controls`    | Edit props interactively   |
| Actions     | `@storybook/addon-ondevice-actions`     | Log component interactions |
| Backgrounds | `@storybook/addon-ondevice-backgrounds` | Change story backgrounds   |
| Notes       | `@storybook/addon-ondevice-notes`       | Add markdown documentation |

© storybookjs · MIT · storybookjs/react-native

Похожие скиллы

Всё по теме «Мобильная разработка» →
storybook-story-writing TheBushidoCollective Пишет и правит истории Storybook для компонентов: формат CSF3, все состояния компонента, сборка без ошибок. Пригодится, когда сториз расползаются и ломают билд. CX Codex +1 673установок react-native alinaqi Скилл задаёт структуру проекта, паттерны компонентов и правила тестирования для React Native. Пригодится, когда агент правит .tsx или код под iOS и Android. CX Codex +1 566установок react-native-design Seth Hobson Скилл помогает собирать React Native-приложения со стилями, навигацией и анимациями Reanimated. Пригодится для кроссплатформенной мобильной разработки. CX Codex 15 522установок react-native-expert https://github.com/Jeffallan Скилл для агентов ИИ-кодинга: помогает собирать мобильные приложения на React Native и Expo — навигация, нативные модули, скорость списков, код под iOS и Android. CX Codex +1 4 900установок expo-react-native-typescript Mindrally Скилл задаёт агенту правила разработки мобильных приложений на Expo, React Native и TypeScript: структура файлов, навигация, состояние, тесты. CX Codex +1 2 200установок upgrade-react-native react-native-community Обновляет проекты React Native Community CLI на заданную версию через diff-файлы React Native Upgrade Helper. CX Codex +1 1 300установок

Из того же набора2

Спонсоры проекта

Компании, которые помогают держать аналитику открытой