Closed cjke closed 7 years ago
I believe React Router v4 will natively support hash link scroll functionality.
Cool. Currently doesn't appear to, and ended up at your library by following the github issues (namely the one where you posted this lib as a solution for RR2).
Its obviously still in alpha (beta?) so these things might still take time to be resolved.
Thanks for taking the time to answer
Currently React Router is on 4.0.0-beta.7, no luck still 😪
Here's a quick workaround for v4. You have to create a HashLink
component and use it instead of Link
when linking to hash fragments because v4 lacks a centralized router onUpdate hook.
@cjke, @revelt let me know if this works for you.
I will also see if I can make a PR to RRv4 with this addition so it's natively supported in the Link
component (or failing that I'll publish it on npm).
// in HashLink.js
import React from 'react';
import { Link } from 'react-router-dom';
export function HashLink(props) {
function hashLinkScroll(event) {
if (props.onClick) props.onClick(event);
// Push onto callback queue so it runs after the DOM is updated
setTimeout(() => {
const { hash } = window.location;
if (hash !== '') {
const id = hash.replace('#', '');
const element = document.getElementById(id);
if (element) element.scrollIntoView();
}
}, 0);
}
return <Link {...props} onClick={hashLinkScroll}>{props.children}</Link>;
}
// in YourComponent.js
...
import { HashLink as Link } from './path-to-file/HashLink';
...
// use just like a RRv4 link:
<Link to="/some/path#with-hash-fragment">Link to Hash Fragment</Link>
I just published this on npm (see readme for instructions):
$ npm install --save react-router-hash-link
import { HashLink as Link } from 'react-router-hash-link';
...
Just curious if v4 is on the roadmap for this library