Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Open <Link> at top of page

I'm using React Router 4 and when I use <Link> the new page doesn't open at the top of the page. Do I need to tell <Link> something specific?

<Link to="/mypage">My Page</Link>
like image 654
bp123 Avatar asked Aug 09 '17 06:08

bp123


Video Answer


1 Answers

I found a pretty solid answer for this in the answer to a similar question. It worked for me anyway so I thought I would share.

For your situation, in the component for "/mypage" add window.scrollTo(0, 0); to the componentDidMount function. Something like this:

import ...
export default class MyPage extends Component {
    constructor(props) {
        super(props);

        this.state = {
            ...
        };
    }

    componentDidMount() {
        window.scrollTo(0, 0);
    }

    render() {
        return (
            ...
        )
    }
}

The Link component will handle navigating to the new path and once the new component is mounted, it will automatically scroll to the top.

like image 91
Aaron Pennington Avatar answered Sep 19 '22 06:09

Aaron Pennington