Created
May 9, 2019 09:56
-
-
Save todesstoss/269547e9f437758caf072742bbe9fec1 to your computer and use it in GitHub Desktop.
React Context snippet
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
export const CONSTANT = 'CONSTANT'; |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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; |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
export { default as withExampleContext } from './withExampleContext'; | |
export * from './constants'; | |
export { | |
default, | |
ExampleContextConsumer, | |
ExampleContextProvider, | |
useExampleContext, | |
} from './ExampleContext'; |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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