Last active
February 19, 2018 02:30
-
-
Save carvallegro/6167b34b0cdf9b6b19cb4358320d5856 to your computer and use it in GitHub Desktop.
ReactHOC
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
import PropTypes from 'prop-types' | |
import {compose, withState, withHandler} from 'recompose' | |
import {connect} from 'react-redux' | |
import {disconnectUser} from '../actions' | |
// Stateless component: only display the JSX with the given props. | |
const menuRender = ({isOpen, toggle, userInfo, disconnect}) => | |
<ul class="menu" hidden={isOpen}> | |
<li><a href="/home">Home</a></li> | |
{userInfo && <li>{userInfo.name}'s Profile</li>} | |
<li><a onClick={() => toggle()}>Close</a></li> | |
{userInfo && <li><a onClick={() => disconnect()}>Disconnect</a></li>} | |
</ul>; | |
// You still can set prop types on a stateless component. | |
menuRender.propTypes = { | |
isOpen: PropTypes.bool.isRequired, | |
toggle: PropTypes.func.isRequired, | |
userInfo: PropTypes.instanceOf(UserInfo) | |
}; | |
// Higher Order Function: We use the recompose library to create a HOF with the open mechanism. | |
const openFn = compose( | |
withState('isOpen', 'setOpen', 0), | |
withHandlers({ | |
toggle: ({ isOpen, setOpen }) => () => setCounter(!isOpen) | |
}) | |
); | |
// Higher Order Component: We enrich the menuRenderer component using the openFn HOF. | |
const Menu = openFn(menuRender); | |
// Defining the two parameters for the connect function | |
const mapStateToProps=state => ({ | |
userInfo => state.users.connectedUser | |
}); | |
const mapDispatchToProps= dispatch => ({ | |
disconnect => dispatch(disconnectUser()); | |
}); | |
// Creating the connect Higher Order Function | |
const reduxHoF = connect(mapStateToProps, mapDispatchToProps); | |
// Enriching our component by linking the props to Redux | |
const ConnectedMenu = reduxHoF(Menu); | |
// ConnectedMenu is now a fully functionnal component that can be closed and open and is linked to Redux! | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment