背景
- 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",
},
// 略
}