Create react provider
Introdution
Providers are a powerful tools in react, we all have used them by popular libraries such as redux
, mobx
, material-ui
.
The thing is, providers can be created even for a smaller purpose than data management and UI library, you can create ModalManager
, translations
injections, NotificationManager
and so much more!
This library creates a Provider for you to use, and a Hoc and a RenderChildrenComponent
for you to use in your sub-components.
Usage
- Installnpm install --save create-react-provider# or yarnyarn add create-react-provider
- import and use!;;constProvider: ThemeProviderHoc: ThemeHocRenderChildren: ThemeRenderChildren=;// ****************// Use provider in top layer of your react app// ****************{return<ThemeProvider><SomeComponent /></ThemeProvider>;}// ****************// Consume provided props in either way (Hoc or renderChildren)// ****************// renderChildren way{return<ThemeRenderChildrenrender=<div style= backgroundColor ><h1 style= color: titleColor >I'm a title!</h1></div>)}/>);}}// Higher order component way@ThemeHoc(ctx => ({titleColor: ctx.primaryColor,backgroundColor: ctx.secondaryColor,}))class SomeComponentUsingHoc extends Component {render() {const { titleColor, backgroundColor } = this.props;return (<div style={{ backgroundColor }}><h1 style={{ color: titleColor }}>I'm a title!</h1></div>;}// You can override Hoc props<SomeComponentUsingHoc /> // Will use titleColor from provider<SomeComponentUsingHoc titleColor="red" /> // Will use from given prop