Ecosyste.ms: Awesome

An open API service indexing awesome lists of open source software.

Awesome Lists | Featured Topics | Projects

https://github.com/BrOrlandi/react-context-connector

React HOC to the new Context API to keep the use as simple as React-Redux connect HOC.
https://github.com/BrOrlandi/react-context-connector

Last synced: about 2 months ago
JSON representation

React HOC to the new Context API to keep the use as simple as React-Redux connect HOC.

Awesome Lists containing this project

README

        

# react-context-connector
[![npm version](https://badge.fury.io/js/react-context-connector.svg)](https://badge.fury.io/js/react-context-connector)
[![Build Status](https://travis-ci.com/BrOrlandi/react-context-connector.svg?branch=master)](https://travis-ci.com/BrOrlandi/react-context-connector)
[![Coverage Status](https://coveralls.io/repos/github/BrOrlandi/react-context-connector/badge.svg?branch=master)](https://coveralls.io/github/BrOrlandi/react-context-connector?branch=master)

React HOC to the new Context API to keep the use as simple as React-Redux connect HOC.

## Usage

* * *

### connectContext(ContextProvider, mapContextToProps)

Generates a HOC to wrap a component with context values in props.

**Parameters**

**ContextProvider**: `Object`, an Object with `Consumer` attribute, like the Context object or a Custom Provider

**mapContextToProps**: `function`, a functiona that receives the context from `Context.Consumer` and returns a object to be used as props for the wrapped component.

**Returns**: `Component`, A HOC which pass context state into props to child component.

* * *

## Example

### Create your Context Provider

```js
const CounterContext = React.createContext();

class CounterProvider extends Component {
state = {
count: 0,
incrementCount: () => {
...
},

decrementCount: () => {
...
},
}

render() {
return (

{this.props.children}

);
}
}

CounterProvider.Consumer = CounterContext.Consumer;
```

### Create your component and connect it to the Context

```js
import connectContext from 'react-context-connector';
import CounterProvider from './CounterProvider';

const CounterDisplay = ({ value }) => (


Counter: {value}

);

CounterDisplay.propTypes = {
value: PropTypes.number,
};

// map context state and functions to component props
const mapContextToProps = context => ({
value: context.count,
});

const CounterDisplayWithContext = connectContext(CounterProvider,mapContextToProps)(CounterDisplay);

export default CounterDisplayWithContext;
```

### Create your App and wrap with the Context Provider

```js
const App = () => (






);

render(, document.getElementById("root"));
```

Check the example folder for more details.