-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathconsumer.js
40 lines (35 loc) · 1001 Bytes
/
consumer.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
/*
* this is a higher-order component (HOC) which simplifies the code as follows:
*
* instead of
*
* export default MyComponent = ({ ...props }) => (
* <StoreContext.Consumer>
* {({ myStoreFunction }) => (
* <Button onClick={() => myStoreFunction()}>Click Me</Button>
* )
* </StoreContext.Consumer>
* )
*
* you can do this:
*
* const MyComponent = ({ myStoreFunction, ...props }) => (
* <Button onClick={() => myStoreFunction()}>Click Me</Button>
* )
*
* export default consumer('myStoreFunction')(MyComponent)
*/
import React from 'react';
import StoreContext from './context';
const consumer = (...propertyNames) => (Component) => (props) => (
<StoreContext.Consumer>
{(storeState) => {
const properties = {};
propertyNames.map((propertyName) => {
properties[propertyName] = storeState[propertyName];
});
return <Component {...properties} {...props} />;
}}
</StoreContext.Consumer>
);
export default consumer;