Skip to content

Commit

Permalink
fix(I18n): Improve hocs proptypes handling + expose proptypes
Browse files Browse the repository at this point in the history
  • Loading branch information
CPatchane committed Jun 17, 2019
1 parent f72b635 commit 91aa079
Show file tree
Hide file tree
Showing 3 changed files with 26 additions and 14 deletions.
22 changes: 14 additions & 8 deletions react/I18n/index.jsx
Original file line number Diff line number Diff line change
Expand Up @@ -74,14 +74,20 @@ I18n.childContextTypes = i18nContextTypes

// higher order decorator for components that need `t` and/or `f`
export const translate = () => WrappedComponent => {
const Wrapper = (props, context) => (
<WrappedComponent
{...props}
t={context.t}
f={context.f}
lang={context.lang}
/>
)
const Wrapper = (props, context) => {
return (
<WrappedComponent
{...props}
t={context.t}
f={context.f}
lang={context.lang}
/>
)
}
Wrapper.propTypes = {
...(WrappedComponent.propTypes || {}),
...i18nContextTypes
}
Wrapper.contextTypes = i18nContextTypes
return Wrapper
}
Expand Down
12 changes: 9 additions & 3 deletions react/I18n/withLocales.jsx
Original file line number Diff line number Diff line change
Expand Up @@ -19,15 +19,21 @@ const withLocales = localesOrRequire => Component => {

class Wrapped extends React.Component {
render() {
// Do not pass t downwards
const { lang, ...rest } = omit(this.props, 't')
const { lang } = this.props
// Do not pass translate props downwards
// since the component is already augmented with translate()
const wrappedProps = omit(this.props, Object.keys(I18n.childContextTypes))
return (
<I18n dictRequire={requireLocale} lang={lang}>
<Translated {...rest} />
<Translated {...wrappedProps} />
</I18n>
)
}
}
Wrapped.propTypes = {
...(Component.propTypes || {}),
...I18n.childContextTypes
}

Wrapped.displayName = `withLocales(${Component.displayName ||
Component.name})`
Expand Down
6 changes: 3 additions & 3 deletions react/I18n/withLocales.spec.jsx
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,7 @@ const componentLocales = {
}
}

class Component extends React.Component {
class MockComponent extends React.Component {
render() {
const { t } = this.props
return <div>{t('hello-world')}</div>
Expand Down Expand Up @@ -48,9 +48,9 @@ describe('with locales', () => {
})
}

const TComponentObj = withLocales(componentLocales)(Component)
const TComponentObj = withLocales(componentLocales)(MockComponent)
const requireLang = lang => componentLocales[lang]
const TComponentFunc = withLocales(requireLang)(Component)
const TComponentFunc = withLocales(requireLang)(MockComponent)

testComponent(TComponentObj, 'locales from object')
testComponent(TComponentFunc, 'locales from require function')
Expand Down

0 comments on commit 91aa079

Please sign in to comment.