Skip to content

Instantly share code, notes, and snippets.

@elis
Created March 11, 2019 10:51
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save elis/937ff5d541dc5af3c2e02473b6396047 to your computer and use it in GitHub Desktop.
Save elis/937ff5d541dc5af3c2e02473b6396047 to your computer and use it in GitHub Desktop.
import React from 'react'
import { withMultiContext } from 'with-context'
const contexts = (ctx => {
const results = []
let keys = ctx.keys()
let values = keys.map(ctx)
for (const [index, dir] of Object.entries(keys)) {
const match = dir.match(/^\.\/([^/]+)$/)
if (!match) continue
const [, contextName] = match
const module = values[index]
const propName = contextName.toLowerCase()
results.push({
contextName, module, propName
})
}
return results
})(require.context('./', true, /^\.\/(?!.*(js|\/))[A-Z].*$/))
const withContext = withMultiContext(contexts.reduce((o, el) => ({
...o,
[el.propName]: el.module.Context
}), {}))
const exportise = contexts.reduce((o, el) => ({
...o,
[`with${el.contextName}`]: withMultiContext({
[el.propName]: el.module.Context
})
}), {withContext})
export default exportise
export const ContextProvider = props => contexts.reduce(
(content, Context) => (<Context.module.Provider>{content}</Context.module.Provider>),
props.children
)
import Context from './context'
const { withUser } = Context
export default withUser(props => <div>Props.user is: {props.user}</div>)
import { withUser } from './context'
export default withUser(props => <div>Props.user is: {props.user}</div>)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment