Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does my react-router link bring me to the middle of a page?

I've got many links on my site but only one that does this.

Instead of bringing me to the top with the navbar, it just goes to the middle of the content. Any idea why this could be?

It is a page that has has a .map going through some JSON, which is rendering div elements of text down the page...if it matters.

Here is some code that might be relevant.

The Route

<Route exact path ="/reviews" component={Reviews} />

The Link

                <Link to="/reviews">
                <ViewAllBtn>View All</ViewAllBtn>
            </Link>

Landing page (lands in the middle instead of top)

        <MotherDiv>
        <NavBar />
        <Prompt>
            <PromptHead>Customer Reviews</PromptHead>
            <PromptBody>Heres what our loyal customers think of Heavenly Details.</PromptBody>
        </Prompt>
        <ReviewsDiv>
            {reviews.map(review =>
                <ReviewDiv key={review.name}>
                    <Name>{review.name}</Name>
                    <Body>{review.body}</Body>
                </ReviewDiv >
            )}
        </ReviewsDiv>
        <Footer />
    </MotherDiv>
like image 883
Jacob Broughton Avatar asked Dec 08 '22 11:12

Jacob Broughton


1 Answers

react-router renders a new component when the URL changes instead of hard refreshing the page. This has a nasty side effect that it remembers your current scroll position and doesn't automatically scroll back to the top of the page when the page changes.

I guess by the sound of your question that this might be the problem here. If it is, than it's quite easy to counteract this issue with a simple higher order component:

class ScrollToTop extends Component {
  componentDidUpdate(prevProps) {
    const { location } = this.props;
    if (location.pathname !== prevProps.location.pathname) {
      window.scrollTo(0, 0);
    }
  }

  render() {
    const { children } = this.props;
    return children;
  }
}

export default withRouter(ScrollToTop);

Wrap this component around your App like this:

render(
  <ScrollToTop>
    <App />
  </ScrollToTop>,
  document.getElementById('app'),
);

And your app should now automatically reset it's scroll position when the route changes.

like image 107
Luze Avatar answered Dec 31 '22 02:12

Luze