Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

React Context Consumer as a HOC #12724

Closed
mmk0083 opened this issue May 1, 2018 · 1 comment
Closed

React Context Consumer as a HOC #12724

mmk0083 opened this issue May 1, 2018 · 1 comment

Comments

@mmk0083
Copy link

mmk0083 commented May 1, 2018

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?

@mmk0083 mmk0083 closed this as completed May 1, 2018
@mmk0083
Copy link
Author

mmk0083 commented May 1, 2018

I just realized you already had this idea and have it in the actual Context API documentation! Sorry for the duplication.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant