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

How can I get the data of context consumer outside the render function ? #5

Closed
rajqumar opened this issue Jul 26, 2018 · 2 comments
Closed

Comments

@rajqumar
Copy link

rajqumar commented Jul 26, 2018

//create a react context
const URLContext = React.createContext();
//create a provider for the urlcontext

class URLProvider extends Component {
  state = {
    url: Router.router.route
  }
  render() {
    return (
      <URLContext.Provider value={this.state} >
        {this.props.children}
      </URLContext.Provider>
    );
  }
}

I created a HOC component

import Menu from './Menu';

const WithContext = (Menu) => {
  return (props) => (
      <URLProvider.Consumer>
           {context =>  <Menu {...props} context={value} />}
      </URLProvider.Consumer>
  }
}

@wesbos
Copy link
Owner

wesbos commented Sep 24, 2018

thats exactly how you do it - create a HOC :)

@wesbos wesbos closed this as completed Sep 24, 2018
@pupretiDev
Copy link

pupretiDev commented Apr 20, 2020

I think there are two issues with the above code:

  1. Instead of <URLProvider.Consumer> we should use <URLContext.Consumer>
  2. And also while wrapping inside consumer, context as property being passed to Menu component should be equal to 'context' which is the param of render Prop.

Combining both:

import Menu from './Menu';

const WithContext = (Menu) => {
return (props) => (
<URLContext.Consumer>
{context => <Menu {...props} context={context} />}
</URLContext.Consumer>
}
}

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

3 participants