Skip to content

Commit

Permalink
Merge pull request #802 from zhouyuan1990/master
Browse files Browse the repository at this point in the history
use forwardRef for withTranslation
  • Loading branch information
jamuhl authored Mar 25, 2019
2 parents b251e68 + 8cd287e commit dc84fbd
Show file tree
Hide file tree
Showing 2 changed files with 16 additions and 6 deletions.
15 changes: 9 additions & 6 deletions src/withTranslation.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,23 +2,26 @@ import React from 'react';
import { useTranslation } from './useTranslation';
import { getDisplayName } from './utils';

export function withTranslation(ns) {
export function withTranslation(ns, options = {}) {
return function Extend(WrappedComponent) {
function I18nextWithTranslation(props) {
function I18nextWithTranslation(props, ref) {
const [t, i18n, ready] = useTranslation(ns, props);

return React.createElement(WrappedComponent, {
const passDownProps = {
...props,
t,
i18n,
tReady: ready,
});
};
if (options.withRef && ref) {
passDownProps.ref = ref;
}
return React.createElement(WrappedComponent, passDownProps);
}

I18nextWithTranslation.displayName = `withI18nextTranslation(${getDisplayName(
WrappedComponent,
)})`;

return I18nextWithTranslation;
return options.withRef ? React.forwardRef(I18nextWithTranslation) : I18nextWithTranslation;
};
}
7 changes: 7 additions & 0 deletions test/withTranslation.spec.js
Original file line number Diff line number Diff line change
Expand Up @@ -19,4 +19,11 @@ describe('withTranslation', () => {
// console.log(wrapper.debug());
expect(wrapper.contains(<div>test</div>)).toBe(true);
});

it('should has ref', () => {
const HocElement = withTranslation('translation', { withRef: true })(TestComponent);
const hocRef = React.createRef();
const parentWrapper = mount(<HocElement ref={hocRef} />);
expect(hocRef.current).not.toBeNull();
});
});

0 comments on commit dc84fbd

Please sign in to comment.