https://github.com/tableflip/react-provide
React Components for putting a value in context and fishing it out
https://github.com/tableflip/react-provide
Last synced: about 1 year ago
JSON representation
React Components for putting a value in context and fishing it out
- Host: GitHub
- URL: https://github.com/tableflip/react-provide
- Owner: tableflip
- License: mit
- Created: 2017-10-11T14:27:26.000Z (over 8 years ago)
- Default Branch: master
- Last Pushed: 2018-01-23T08:51:54.000Z (over 8 years ago)
- Last Synced: 2025-03-18T13:19:31.690Z (over 1 year ago)
- Language: JavaScript
- Size: 49.8 KB
- Stars: 2
- Watchers: 2
- Forks: 0
- Open Issues: 0
-
Metadata Files:
- Readme: README.md
- License: LICENSE
Awesome Lists containing this project
README
# react-provide
[](https://david-dm.org/tableflip/react-provide) [](https://standardjs.com)
> React Components for putting a value in context and fishing it out. Avoids deep chains of prop passing.
## Install
```sh
npm install react-provide
```
## Usage
**api.js**
```js
import { contextProvider, withContext } from 'react-provide'
export default class Api {
getItems: () => ['some', 'items']
}
// Create a Provider that'll put and object called 'api' into context
export const Provider = contextProvider('api')
// Create a helper that pulls 'api' out of context and passes it as a prop
export const withApi = withContext('api')
```
**list.js**
```js
import React from 'react'
import { withApi } from './api'
// Use withApi to pass 'api' as a prop to the component
export default withApi(({ api }) => (
{api.getItems().map((name) => name)}
))
```
**main.js**
```js
import React from 'react'
import ReactDOM from 'react-dom'
import Api, { Provider } from './api'
import List from './list'
// Use the Provider so deeply nested components can use the api in context
ReactDOM.render(
,
document.getElementById('root')
)
```
## API
### `contextProvider(key)`
Create a provider component that can be used to provide a value called `key` to nested components in context.
e.g.
```js
import { contextProvider } from 'react-provide'
const Provider = contextProvider('foo')
{/* your component tree */}
```
### `withContext(key)`
Create a function that'll create a component to pull a value called `key` from context and pass it as a prop to your component.
e.g.
```js
import { withContext } from 'react-provide'
class MyComponent extends Component {
static propTypes = {
foo: PropTypes.object.isRequired
}
render () {
return
{this.props.foo}
}
}
export default withContext('foo')(MyComponent)
```
## Contribute
Feel free to dive in! [Open an issue](https://github.com/tableflip/react-provide/issues/new) or submit PRs.
## License
[MIT](LICENSE) © Alan Shaw