Created
April 29, 2020 22:49
-
-
Save ZenulAbidin/7c006b830e903d01a343538b73aedbae to your computer and use it in GitHub Desktop.
Makes HTML anchors defined with ref work with HashRouters in react apps.
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
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