Last active
April 20, 2018 16:42
-
-
Save erick2014/7f6a8869161e332de268454b48a040cd to your computer and use it in GitHub Desktop.
HOC in react, simple demo
This file contains 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
/***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