Skip to content

Instantly share code, notes, and snippets.

@carvallegro
Last active February 19, 2018 02:30
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 carvallegro/6167b34b0cdf9b6b19cb4358320d5856 to your computer and use it in GitHub Desktop.
Save carvallegro/6167b34b0cdf9b6b19cb4358320d5856 to your computer and use it in GitHub Desktop.
ReactHOC
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