Skip to content

Instantly share code, notes, and snippets.

@todesstoss
Created May 9, 2019 09:56
Show Gist options
  • Save todesstoss/269547e9f437758caf072742bbe9fec1 to your computer and use it in GitHub Desktop.
Save todesstoss/269547e9f437758caf072742bbe9fec1 to your computer and use it in GitHub Desktop.
React Context snippet
export const CONSTANT = 'CONSTANT';
import React, { createContext } from 'react';
import * as constants from './constants';
const ExampleContext = createContext();
const { Consumer, Provider } = ExampleContext;
const UserProvider = ({ children }) => {
return <Provider value={{}}>{children}</Provider>;
};
const useExampleContext = () => useContext(ExampleContext);
export { Consumer as UserConsumer, UserProvider, useExampleContext };
export default ExampleContext;
export { default as withExampleContext } from './withExampleContext';
export * from './constants';
export {
default,
ExampleContextConsumer,
ExampleContextProvider,
useExampleContext,
} from './ExampleContext';
import React from 'react';
import hoistStatics from 'hoist-non-react-statics';
import getComponentDisplayName from '~/utils/getComponentDisplayName';
import { useExampleContext } from './ExampleContext';
function withExampleContext(ComposedComponent) {
const displayName = getComponentDisplayName(ComposedComponent);
const WithExampleContextWrapper = (props) => {
const example = useExampleContext;
return <ComposedComponent data={{ ...example }} {...props} />;
};
WithExampleContextWrapper.displayName = `withExampleContext(${displayName})`;
return hoistStatics(WithExampleContextWrapper, ComposedComponent);
}
export default withExampleContext;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment