Skip to content

React Context Consumer as a HOC #12724

@mmk0083

Description

@mmk0083

Do you want to request a feature or report a bug?

feature

Which versions of React, and which browser / OS are affected by this issue? Did this work in previous versions of React?

React 16.3

Just wanted to put an idea out here for feedback to see if this would be something useful. I've been using the new context API a bit and noticed myself repeating a pattern. A lot of my components look something like:

const MyContext = React.createContext('foo');

const MyComponent = ({ ownProp }) => (
  <MyContext.Consumer>
    { myProp => <div>{ myProp }{ ownProp }</div>
  </MyContext.Consumer>
);
export default MyComponent;

This got me to wondering. What if the Consumer could be exposed as a HOC?

const MyContext = React.createContext('foo');

const MyComponent = ({ myProp, ownProp }) => (
  <div>{ myProp }{ ownProp }</div>
);
export default MyContext.isConsumedBy(MyComponent);

This is similar to connect from redux or withRouter from react-router in which the context value(s) are being injected by a HOC. I can write my own HOC to do this using the existing Consumer component from the Context API - but thought I'd put this out here for possible inclusion in the API itself.

const isConsumedBy = Wrapped => props => (
  <MyContext.Consumer>
    { myProp => <Wrapped myProp={myProp} {...props} /> }
  </MyContext.Consumer>
);

Thoughts?

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions