Qiita Teams that are logged in
You are not logged in to any team

Log in to Qiita Team
Community
OrganizationAdvent CalendarQiitadon (β)
Service
Qiita JobsQiita ZineQiita Blog
0
Help us understand the problem. What is going on with this article?
@hiyoko3

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

More than 1 year has passed since last update.

背景

  • 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",
  },
// 
}

参考

0
Help us understand the problem. What is going on with this article?
Why not register and get more from Qiita?
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away
hiyoko3
A Software developer in Tokyo.

Comments

No comments
Sign up for free and join this conversation.
Sign Up
If you already have a Qiita account Login
0
Help us understand the problem. What is going on with this article?