Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Support HOC usage #11

Open
wants to merge 4 commits into
base: master
Choose a base branch
from
Open

Conversation

momocow
Copy link

@momocow momocow commented Sep 13, 2020

The add-on currently does not support to pass the i18n instance via HOC, without any decorator workarounds.


There are 4 ways to integrate react-i18next into components mentioned in the quick-start of react-i18next.

Suppose I have a component as the following one,

import React from 'react'
import { Trans, Translation, useTranslation } from 'react-i18next'

export function MyComp ({ t: t1 }) {
  const { t: t2 } = useTranslation()
  return (
    <div>
      <Trans>A</Trans>
      {t1('A')}
      {t2('A')}
      <Translation>{t3 => t3('A')}</Translation>
    </div>
  )
}

And here is my preview.js,

import i18n from 'i18next'
import  { initReactI18next } from 'react-i18next'
import { withI18next } from 'storybook-addon-i18next'

i18n
  .use(initReactI18next)
  .init({
    lng: 'en',
    resources: { en: { translation: { A: 'Big A' } } }
  })

export const decorators = [
  withI18next({
    i18n,
    languages: {
      en: 'English'
    }
  })
]

There will be a TypeError on rendering MyComp, which is arguing that TypeError: t1 is not a function.


To work around this error with the current version of the add-on, i.e. v1.3.0, the following decorator should be added.

import { withTranslation } from 'react-i18next'

const workAround = (Story, context) => React.createElement(
  withTranslation()(props => Story({
    ...context, args: { ...context.args, ...props }
  })
)

// preview.js
decorators.push(workAround)

In this work around, withTranslation is used to generate i18n props, i.e. t, tReady and i18n, and an anonymous FC takes those props, injects them into context.args, and invoke the Story rendering.


In this pull request, I made the workAround decorator integrated into the add-on directly. Please take a review on this PR and let me know it if there is any concerns or problems.

Thank you for the nice add-on.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

1 participant