Reputation: 2836
I learn some React-router-dom and it's kind of working but since I have three Components
one after the other like a long page. Then When I click about
button like this in the top menu;
<Button variant="primary" onClick={() => history.push('/articles')}>
Articles
</Button>
<Button variant="primary" onClick={() => history.push('/stories')}>
Stories
</Button>
<Button variant="primary" onClick={() => history.push('/about')}>
About
</Button>
The /about
page is rendered but not scrolled to because it's page number 3. Is there some way to auto scroll to the page?
My menu is not fixed but whenever user scroll up the menu appear and when user scroll down the menu is gone to not block content.
It looks like this three Components forming a long page
Is there maybe something built into react router or useHistory
or do I have to figure out some way to make the Components know they are being summoned from main Menu? and then themselves calculate how to scroll to become visible.
I know little React Redux and was thinking I could dispatch and action from the Menu button and mapStateToProp
listen for the action in the Component, that then will scroll visible. Feels like a bad hack don't know.
Upvotes: 3
Views: 1429
Reputation: 197
in the the answer above said by Dmitriy Sakhno it gives an error I think because it cann't find it because the page haven't render yet so I used setTimeout and it worked.
const onAboutPageClick = () => {
history.push('/about')
setTimeout(() => {
const aboutPageNode = document.getElementById('aboutPage');
aboutPageNode.scrollIntoView({behavior: "smooth"});
}, 0);
}
Upvotes: 1
Reputation: 553
not sure if this works or if this consistent/best solution, but as far as here is no other answers you could try to use this
const onAboutPageClick = () =>{
const aboutPageNode = document.getElementById('aboutPage')
aboutPageNode.scrollIntoView({behavior: "smooth"});
history.push('/about')
}
<Button variant="primary" onClick={() => history.push('/articles')}>
Articles
</Button>
<Button variant="primary" onClick={() => history.push('/stories')}>
Stories
</Button>
<Button variant="primary" onClick={onAboutPageClick}>
About
</Button>
..... some other html code
<div id="aboutPage"> Here is about page </div>
Upvotes: 2