Created
February 28, 2018 16:54
-
-
Save hadrienl/167a7e94a3d0e56dc2de6f70b0c82142 to your computer and use it in GitHub Desktop.
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 { Link } from 'react-router'; | |
const withLink = WrappedComponent => class WithLink extends React.Component { | |
static contextTypes = { | |
router: PropTypes.shape({ | |
history: PropTypes.shape({ | |
push: PropTypes.func.isRequired, | |
}).isRequired | |
}).isRequired | |
}; | |
componentDidMount() { | |
const { history } = this.context.router; | |
const callback = mutationsList => { | |
for (const mutation of mutationsList) { | |
for (const node of mutation.addedNodes) { | |
if (!node._linksListener) { | |
node._linksListener = node.addEventListener('click', e => { | |
if (e.target.nodeName.toLowerCase() === 'a') { | |
e.preventDefault(); | |
history.push(e.target.getAttribute('href')); | |
} | |
}) | |
} | |
} | |
} | |
}; | |
this._observer = new MutationObserver(callback); | |
this._observer.observe(this.container, { subtree: true, childList: true }); | |
} | |
componentWillUnmount() { | |
this._observer.disconnect(); | |
} | |
render() { | |
return ( | |
<div | |
ref={ i => { this.container = i }}> | |
<WrappedComponent | |
{...this.props} /> | |
</div> | |
); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment