Last active
May 8, 2019 17:08
-
-
Save arlindosilvaneto/41834288e812c7cd9249684d29498381 to your computer and use it in GitHub Desktop.
ReactJS Context API Provider with State and Consumer HOC
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import React, { createContext } from 'react'; | |
const UserContext = createContext(); | |
export default class UserProvider extends React.Component { | |
constructor(props) { | |
super(props); | |
this.state = { | |
user: {}, | |
updateUser: this.updateUser | |
}; | |
} | |
updateUser = (newUser) => { | |
this.setState({ | |
user: newUser | |
}); | |
} | |
render() { | |
return ( | |
<UserContext.Provider value={this.state}> | |
{this.props.children} | |
</UserContext.Provider> | |
) | |
} | |
}; | |
export const withUserContext = Inner => props => { | |
return ( | |
<UserContext.Consumer> | |
{context => { | |
return <Inner user={context.user} updateUser={context.updateUser} {...props} /> | |
}} | |
</UserContext.Consumer> | |
); | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment