Skip to content

Instantly share code, notes, and snippets.

@ZenulAbidin
Created April 29, 2020 22:49
Show Gist options
  • Save ZenulAbidin/7c006b830e903d01a343538b73aedbae to your computer and use it in GitHub Desktop.
Save ZenulAbidin/7c006b830e903d01a343538b73aedbae to your computer and use it in GitHub Desktop.
Makes HTML anchors defined with ref work with HashRouters in react apps.
componentDidMount() {
// Other initialization...
// IMPORTANT: Put this after "document.body.classList.toggle"
let hash = this.props.location.hash.replace('#', '');
if (hash) {
let node = ReactDOM.findDOMNode(this.refs[hash]);
if (node) {
node.scrollIntoView();
}
}
}
componentDidUpdate() {
let hash = this.props.location.hash.replace('#', '');
if (hash) {
let node = ReactDOM.findDOMNode(this.refs[hash]);
if (node) {
node.scrollIntoView();
}
}
}
// Usage:
// /component-a
// <h3 ref='scroll_here'>Scroll to here</h3>
// ...
// /component-b
// <a href="/component-b#scroll_here">Scrolls to h3</a>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment