Created
July 30, 2017 19:20
-
-
Save headzoo/8f4c6a5e843ec26abdcad87cd93e3e2e to your computer and use it in GitHub Desktop.
Wraps the React Router Link component and creates a delay after the link is clicked.
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 { Link } from 'react-router-dom'; | |
/** | |
* Wraps the React Router Link component and creates a delay after the link is clicked. | |
*/ | |
export default class DelayLink extends React.Component { | |
static propTypes = { | |
/** | |
* Milliseconds to wait before registering the click. | |
*/ | |
delay: PropTypes.number, | |
/** | |
* Called after the link is clicked and before the delay timer starts. | |
*/ | |
onDelayStart: PropTypes.func, | |
/** | |
* Called after the delay timer ends. | |
*/ | |
onDelayEnd: PropTypes.func | |
}; | |
static defaultProps = { | |
delay: 0, | |
onDelayStart: () => {}, | |
onDelayEnd: () => {} | |
}; | |
static contextTypes = Link.contextTypes; | |
constructor(props) { | |
super(props); | |
this.timeout = null; | |
} | |
componentWillUnmount() { | |
if (this.timeout) { | |
clearTimeout(this.timeout); | |
} | |
} | |
/** | |
* Called when the link is clicked | |
* | |
* @param {Event} e | |
*/ | |
handleClick = (e) => { | |
const { replace, to, delay, onDelayStart, onDelayEnd } = this.props; | |
const { history } = this.context.router; | |
onDelayStart(e, to); | |
if (e.defaultPrevented) { | |
return; | |
} | |
e.preventDefault(); | |
this.timeout = setTimeout(() => { | |
if (replace) { | |
history.replace(to); | |
} else { | |
history.push(to); | |
} | |
onDelayEnd(e, to); | |
}, delay); | |
}; | |
render() { | |
const props = Object.assign({}, this.props); | |
delete props.delay; | |
delete props.onDelayStart; | |
delete props.onDelayEnd; | |
return ( | |
<Link {...props} onClick={this.handleClick} /> | |
); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Another thing this component is missing is the ability to carry over props such as className or onLeave etc. Is there a clean way to do this whilst still maintaining typescript support for these props?