Skip to content

Instantly share code, notes, and snippets.

@erick2014
Last active April 20, 2018 16:42
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save erick2014/7f6a8869161e332de268454b48a040cd to your computer and use it in GitHub Desktop.
Save erick2014/7f6a8869161e332de268454b48a040cd to your computer and use it in GitHub Desktop.
HOC in react, simple demo
/***define the Home component here***/
import React, { Component } from 'react'
class Home extends Component {
componentDidMount () {
// dispatch action to fetch users
this.props.fetchUsers()
}
render () {
console.log('here we have users available from redux store ', this.props)
return (
<div className='container'>
<h1>Hello from my React Component!</h1>
</div>
)
}
}
// bind component to the store
export default Home
/***define the Home component here***/
/**** define the Hoc component****/
import React, { Component } from 'react'
import userActions from 'reduxConfig/actions/users'
// redux stuff
import { connect } from 'react-redux'
function Hoc (WrappedComponent) {
class HocTest extends Component {
render () {
return (
<WrappedComponent {...this.props} />
)
}
}
// connect component to the redux store
return connect(
// map props
state => ({users: state.users}),
// map actions
{fetchUsers: userActions.fetchUsers}
)(HocTest)
}
export default Hoc
/**** define the Hoc component****/
/**** Get the component Home passing it through the HOC****/
const TestHoc = Hoc(Home)
class App extends Component {
render () {
return (
<div>
<Route exact path='/' component={TestHoc} />
<Route exact path='/contact' component={Contact} />
</div>
)
}
}
const MyApp = () => {
return (
<Provider store={store}>
<Router history={history}>
<App />
</Router>
</Provider>
)
}
// render our App componnet and mount it to our #root element
ReactDOM.render(<MyApp />, document.getElementById('root'))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment