LoginSignup
5
0

More than 3 years have passed since last update.

Storybook + React.jsでViewにロジックや静的ファイルを導入する

Last updated at Posted at 2019-08-18

背景

  • Storybook とはコンポーネント毎にViewを可視化するツールです。
  • i18nなどでテキストを管理していたため動的にファイルを変更させたかったのですが、公式ドキュメントなどを記述がありませんでしたので補足です。

下記のように記述すると、エラーで怒られます。

こんな風に使いたかった
import * as React from 'react'
import { useTranslation } from 'react-i18next'

// react-i18next を呼ぶ時は別途スクリプトの記述が必要ですが略
// 公式を参照するとわかります。
// https://github.com/i18next/react-i18next

storiesOf("HelloWorld", module)
  .add("HelloWorld", () => {
    const { t } = useTranslation()
    return (
      <HelloWorld>t('hello_world')</HelloWorld>
    )
  })
エラーメッセージ
Invariant Violation: Invalid hook call. Hooks can only be called inside of the body of a function component. This could happen for one of the following reasons:
1. You might have mismatching versions of React and the renderer (such as React DOM)
2. You might be breaking the Rules of Hooks
3. You might have more than one copy of React in the same app
See https://fb.me/react-invalid-hook-call for tips about how to debug and fix this problem.

解決策

React.createElementを導入します。

これだと動きます
import * as React from 'react'
import { useTranslation } from 'react-i18next'

storiesOf("HelloWorld", module)
  .add("HelloWorld", () => 
    React.createElement(() => {
      const { t } = useTranslation()
      return (
        <HelloWorld>t('hello_world')</HelloWorld>
      )
    })
  )

静的ファイルの参照方法

webpackの出力先をstorybookにも適用してあげるだけです。-sオプションを使用します。

下記は webpackの出力先がdistの場合

package.json
{
// 
"scripts": {
    "storybook": "start-storybook -p 9001 -c .storybook -s ./dist",
  },
// 
}

参考

5
0
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
5
0