Skip to content

Commit 3c6c0bd

Browse files
authored
Merge pull request #5 from 4Catalyzer/additions
feat: add injectContextAsProp
2 parents 9f35033 + cf07839 commit 3c6c0bd

File tree

3 files changed

+38
-3
lines changed

3 files changed

+38
-3
lines changed

src/forwardRef.js

Lines changed: 14 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -2,10 +2,21 @@ import React from 'react';
22

33
export default function forwardRef(
44
renderFn,
5-
{ displayName, propTypes, defaultProps },
5+
{ displayName, propTypes, defaultProps, allowFallback = false },
66
) {
77
const render = (...args) => renderFn(...args);
88

9-
Object.assign(render, { displayName, propTypes, defaultProps });
10-
return React.forwardRef(render);
9+
Object.assign(render, { displayName });
10+
11+
if (React.forwardRef || !allowFallback)
12+
return Object.assign(React.forwardRef(render), {
13+
propTypes,
14+
defaultProps,
15+
});
16+
17+
return Object.assign(props => render(props, null), {
18+
displayName,
19+
propTypes,
20+
defaultProps,
21+
});
1122
}

src/injectContextAsProp.js

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,4 @@
1+
import mapContextToProps from './mapContextToProps';
2+
3+
export default (Context, prop, Component) =>
4+
mapContextToProps(Context, context => ({ [prop]: context }), Component);

test/injectAsProp.test.js

Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,20 @@
1+
import React from 'react';
2+
import { mount } from 'enzyme';
3+
4+
import injectContextAsProp from '../src/injectContextAsProp';
5+
6+
describe('injectContextAsProp', () => {
7+
it('should inject context', () => {
8+
const Mapper = injectContextAsProp(
9+
React.createContext('foo'),
10+
'foo',
11+
props => <div>{props.foo}</div>,
12+
);
13+
14+
expect(
15+
mount(<Mapper />)
16+
.find('div')
17+
.text(),
18+
).toEqual('foo');
19+
});
20+
});

0 commit comments

Comments
 (0)