Reputation: 117
I have a page where each component has scroll functionality. But it will come from another page. Like on the Home page route is "/" I have set the scroll with
import { Link as Scrolllink, animateScroll as scroll } from 'react-scroll'
<Scrolllink
onClick={() => history.push('/services')}
to="DayCare"
spy={true}
smooth={true}
hashSpy={true}
isDynamic={true}
>
Day care
</Scrolllink>
<Scrolllink
onClick={() => history.push('/services')}
to="Office"
spy={true}
smooth={true}
hashSpy={true}
isDynamic={true}
>
Office
</Scrolllink>
Similar to this I have set for all the target elements. Now In-service page I ave added the id of that target before that components
<div id="DayCare"> <DayCare /></div>
<div id="HomeApartment"> <HomeApartment/></div>
<div id="Office"> <Office/></div>
<div id="MoveInOut"> <MoveInOut/></div>
<div id="Construction"> <Construction/></div>
<div id="Airbnb"> <Airbnb/></div>
<div id="Carpet"> <Carpet/></div>
<div id="Infection"> <Infection/></div>
But I am pushing to the "/service" page, but not scrolled to target id: If I click on On the link I going to a random component, not the one I have targeted. How to fix this problem.
Upvotes: 1
Views: 4233
Reputation: 21
I had the same problem with my app and resolve it with async function and scroller from react-scroll:
import React from 'react';
import {scroller} from "react-scroll";
import {useHistory} from "react-router-dom";
const Nav = () => {
const history = useHistory();
const scrollTarget = (target) => scroller.scrollTo(target, {smooth: true, duration: 700});
const scrollToPage = async (target) => {
if (history.location.pathname !=='/') {
await history.push('/');
}
scrollTarget(target);
};
return (
<nav>
<div onClick={() => scrollToPage('about')}>About</div>
<div onClick={() => scrollToPage('info')}>Info</div>
<div onClick={() => scrollToPage('contact')}>Contact</div>
</nav>
);
}
export default Nav;
Upvotes: 2
Reputation: 11
Maybe you can try the react-scrollable-anchor package https://www.npmjs.com/package/react-scrollable-anchor. For me it worked for navigating and scrolling from another page.
Upvotes: 1