Skip to content

Instantly share code, notes, and snippets.

@SimeonC
Last active July 25, 2018 10:43
Show Gist options
  • Save SimeonC/0a4e21c0e5406d28bdde4d824986279f to your computer and use it in GitHub Desktop.
Save SimeonC/0a4e21c0e5406d28bdde4d824986279f to your computer and use it in GitHub Desktop.
React-Cosmos Context proxy
/* eslint-disable react/prop-types */
import React from 'react';
export default (providersMap) => {
const ContextsProxy = (props) => {
const { nextProxy, ...rest } = props;
const { value: NextProxy, next } = nextProxy;
const { contexts } = props.fixture;
if (contexts && Object.keys(contexts).length > 0) {
let result = <NextProxy {...rest} nextProxy={next()} />;
Object.keys(contexts).forEach((key) => {
const Provider = providersMap[key];
result = <Provider value={contexts[key]}>{result}</Provider>;
});
return result;
}
return <NextProxy {...rest} nextProxy={next()} />;
};
return ContextsProxy;
};
import { withShops } from './ShopsContext';
const RenderShops = ({ shops }) => <div>Shops: {shops.join(', ')}</div>;
/*
The two fixtures here will output the correct context of shops as provided by the proxy :)
*/
export default [
{
name: 'Hitchikers',
component: withShops(RenderShops),
context: {
shops: ['Restaurant at the end of the Universe']
}
},
{
name: 'Star Wars',
component: withShops(RenderShops),
context: {
shops: ['Deathstar Cantina', 'Mos Eisley Cantina', 'Jabba\'s Palace']
}
}
];
import { Provider as ShopsProvider } from './ShopsContext';
export default [
createContextsProxy({
shops: ShopsProvider
})
];
import React, { createContext } from 'react';
import { getDisplayName } from '@ts-react-utils/hoc';
export const { Provider, Consumer } = createContext([]);
export function withShops(WrappedComponent) {
const withShopsComponent = (props) => (
<Consumer>
{(shops) => <WrappedComponent {...props} shops={shops} />}
</Consumer>
);
withShopsComponent.displayName = `WithShops(${getDisplayName(
WrappedComponent
)})`;
return withShopsComponent;
}
const shops = [];
const ShopsContext = ({ children }) => (
<Provider value={shops}>{children}</Provider>
);
export default ShopsContext;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment