Created
June 16, 2017 01:46
-
-
Save mksarge/a22c809cdd5698aeb4f57c009a3a4933 to your computer and use it in GitHub Desktop.
A store-connected <Link/> component for declarative navigation. Use with: https://github.com/mksarge/redux-first-routing
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 from 'react'; | |
| import PropTypes from 'prop-types'; | |
| import { connect } from 'react-redux'; | |
| import { push, replace, goBack, goForward } from 'redux-first-routing'; | |
| const Link = (props) => { | |
| const { to, action, onClick, children, dispatch, ...other } = props; | |
| const handleClick = (event) => { | |
| // Ignore any click other than a left click | |
| if ((event.button && event.button !== 0) | |
| || event.metaKey | |
| || event.altKey | |
| || event.ctrlKey | |
| || event.shiftKey | |
| || event.defaultPrevented === true) { | |
| return; | |
| } | |
| // Prevent page reload | |
| event.preventDefault(); | |
| // Execute onClick callback, if it exists | |
| if (onClick) { | |
| onClick(event); | |
| } | |
| // Dispatch the action specified in the props (default: push action) | |
| if (action === 'replace') { | |
| dispatch(replace(to)); | |
| } else if (action === 'back' || action === 'goBack') { | |
| dispatch(goBack()); | |
| } else if (action === 'forward' || action === 'goForward') { | |
| dispatch(goForward()); | |
| } else { | |
| dispatch(push(to)); | |
| } | |
| }; | |
| return (<a href={to} onClick={handleClick} {...other} >{children}</a>); | |
| }; | |
| Link.propTypes = { | |
| to: PropTypes.string.isRequired, | |
| action: PropTypes.string, | |
| onClick: PropTypes.func, | |
| children: PropTypes.node, | |
| dispatch: PropTypes.func.isRequired, | |
| }; | |
| export default connect()(Link); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment