Skip to content

Commit

Permalink
Support ref (#21)
Browse files Browse the repository at this point in the history
* Support forwardRef

* Implement innerRef

* Restore UT
  • Loading branch information
Kaixin authored and SBoudrias committed Mar 21, 2019
1 parent 9a75a78 commit 116b820
Show file tree
Hide file tree
Showing 2 changed files with 36 additions and 3 deletions.
32 changes: 31 additions & 1 deletion __test__/test.js
Original file line number Diff line number Diff line change
Expand Up @@ -69,7 +69,6 @@ describe('<I18nProvider>', () => {
it('children get i18n from I18nProvider', () => {
const LocalizedTest = translate(TestElement);
const WrappedTest = LocalizedTest.WrappedComponent;

expect(<WrappedTest testProp="required" i18n={mockI18n} />).toMatchSnapshot();

const eleWithProvider = mount(
Expand Down Expand Up @@ -126,6 +125,37 @@ describe('translate Component', () => {
const localizedEle = mount(<LocalizedEle i18n={mockI18n} testProp="required" />);
expect(localizedEle).toMatchSnapshot();
});

it('should inherit ref properly', () => {
class A extends React.Component<{ i18n: I18nType }, {}> {
getName = () => 'NameA';

render() {
return <div />;
}
}

const B = translate(A);

class C extends React.Component<{}, {}> {
ref = React.createRef();

test = () => {
const { current } = this.ref;
if (current && typeof current.getName === 'function') {
return current.getName();
}
return '';
};

render() {
return <B innerRef={this.ref} />;
}
}
const Test = mount(<C />);
const instance = Test.instance();
expect(instance.test()).toEqual('NameA');
});
});

describe('mock i18n', () => {
Expand Down
7 changes: 5 additions & 2 deletions src/translate.js
Original file line number Diff line number Diff line change
Expand Up @@ -29,14 +29,17 @@ function translate<Com: React$ComponentType<*>>(
static displayName = `Translate(${name})`;

render() {
const { innerRef, ...restProps } = this.props;

return (
<I18nContext.Consumer>
{i18n => <WrappedComponent i18n={i18n} {...this.props} />}
{i18n => (
<WrappedComponent ref={innerRef} i18n={i18n} {...restProps} />
)}
</I18nContext.Consumer>
);
}
}

return (hoistStatics(Translate, WrappedComponent): any);
}

Expand Down

0 comments on commit 116b820

Please sign in to comment.