11
14

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

[React]Storybook導入までの手順

Last updated at Posted at 2019-02-07

概要

  • ReactアプリでStorybookの環境を作るまでのメモ

手順

アプリの雛形生成

  • ここではcreate-react-appを使う
npx create-react-app react-storybook-sample
cd react-storybook-sample

Storybookのインストール

  • sb initするとpackage.jsonの中を見て自動でReactアプリだと判定してくれる
npx -p @storybook/cli sb init

addonの追加

  • 趣味の範囲であるがここではknobsとinfoを入れる
yarn add -D @storybook/addon-info @storybook/addon-knobs

設定ファイルの修正

  • addの設定を追加
.storybook/addons.js
import '@storybook/addon-actions/register';
import '@storybook/addon-links/register';
import '@storybook/addon-knobs/register'; // <- これを追加
  • configの修正
.storybook/config.js
import { addDecorator, configure } from '@storybook/react';
import { withKnobs } from '@storybook/addon-knobs';
import { withInfo } from '@storybook/addon-info';

addDecorator(withKnobs);
addDecorator(withInfo);

// src/components配下のxxx.stories.jsというファイルを対象とする
const req = require.context('../src/components/', true, /stories.js$/);

function loadStories() {
  req.keys().forEach(req);
}

configure(loadStories, module);

動作確認

サンプルコンポーネントの作成

  • 自動生成されたstoryを消す
rm -rf src/stories
  • コンポーネント作成
mkdir -p src/components/Button
touch src/components/Button/index.js src/components/Button/index.stories.js
  • コンポーネント本体
src/components/Button/index.js
import React from 'react';
import propTypes from 'prop-types';

function Button({ text, onClick }) {
  return (
    <button onClick={onClick} type="button">
      {text}
    </button>
  );
}

Button.propTypes = {
  text: propTypes.string.isRequired,
  onClick: propTypes.func,
};

Button.defaultProps = {
  onClick: null,
};

export default Button;
  • Storyの作成
src/components/Button/index.stories.js
import React from 'react';
import { storiesOf } from '@storybook/react';
import { action } from '@storybook/addon-actions';
import { text } from '@storybook/addon-knobs';
import Button from '.';

const stories = storiesOf('Button', module);

stories.add('ボタンコンポーネント', () => (
  <Button text={text('ラベル', 'Click Me')} onClick={action('Click!')} />
));

Storybookの起動

  • 以下のコマンドでstorybookを起動
yarn storybook
# open http://localhost:9009

デモ

demo.gif

11
14
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
11
14

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?