diff --git a/package.json b/package.json index 2476c57..861043f 100644 --- a/package.json +++ b/package.json @@ -6,7 +6,7 @@ "jsnext:main": "es/index.js", "repository": { "type": "git", - "url": "https://github.com/4Catalyzer/context.git" + "url": "https://github.com/4Catalyzer/react-context-toolbox.git" }, "author": "4Catalyzer", "license": "MIT", diff --git a/src/forwardRef.js b/src/forwardRef.js new file mode 100644 index 0000000..827ea32 --- /dev/null +++ b/src/forwardRef.js @@ -0,0 +1,11 @@ +import React from 'react'; + +export default function forwardRef( + renderFn, + { displayName, propTypes, defaultProps }, +) { + const render = (...args) => renderFn(...args); + + Object.assign(render, { displayName, propTypes, defaultProps }); + return React.forwardRef(render); +} diff --git a/src/mapContextToProps.js b/src/mapContextToProps.js index a8fdbc5..8177227 100644 --- a/src/mapContextToProps.js +++ b/src/mapContextToProps.js @@ -1,4 +1,5 @@ import React from 'react'; +import forwardRef from './forwardRef'; const getDisplayName = Component => { const name = @@ -47,9 +48,10 @@ function $mapContextToProps( } const contextTransform = consumers.length === 1 ? singleRender : multiRender; - contextTransform.displayName = displayName || getDisplayName(Component); - return React.forwardRef(contextTransform); + return forwardRef(contextTransform, { + displayName: displayName || getDisplayName(Component), + }); } export default function mapContextToProps(maybeOpts, mapToProps, Component) { diff --git a/src/transformContext.js b/src/transformContext.js new file mode 100644 index 0000000..bb705cf --- /dev/null +++ b/src/transformContext.js @@ -0,0 +1,17 @@ +import React from 'react'; +import forwardRef from './forwardRef'; + +export default function transformContext(Context) { + return forwardRef( + props => ( + + {context => ( + + {props.children} + + )} + + ), + { displayName: 'ContextTransformer' }, + ); +} diff --git a/test/transformContext.test.js b/test/transformContext.test.js new file mode 100644 index 0000000..b909541 --- /dev/null +++ b/test/transformContext.test.js @@ -0,0 +1,43 @@ +import React from 'react'; +import { mount } from 'enzyme'; + +import transformContext from '../src/transformContext'; + +describe('transformContext', () => { + it('should transform a context value', () => { + const Context = React.createContext('foo'); + const Transformer = transformContext(Context); + + const mapper = jest.fn(value => (value === 'foo' ? value : 'baz')); + + function Inner() { + return {v =>
{v}
}
; + } + function Wrapper() { + return ( + + + + ); + } + + function Nested() { + return ( + + + + ); + } + expect( + mount() + .find('div') + .text(), + ).toEqual('foo'); + + expect( + mount() + .find('div') + .text(), + ).toEqual('baz'); + }); +});