Home > database >  My app doesn't automatically scroll up after adding ScrollToTop Component
My app doesn't automatically scroll up after adding ScrollToTop Component

Time:04-28

First time using React this week and I'm trying to create a fetch Github app, everything is working but the scroll to the top. When I scroll down and click on the view Repo I want the screen to automatically scroll up, I've copied the code via the React Docs and I am using React-Router-Dom version 5 however nothing is scrolling up. Please see below for my code, where am I going wrong guys?

import { useEffect } from "react";
import { useLocation } from "react-router-dom";

export default function ScrollToTop() {
  const { pathname } = useLocation();

  useEffect(() => {
    window.scrollTo(0, 0);
  }, [pathname]);

  return null;
}

App.js

import { BrowserRouter as Router, Switch, Route} from 'react-router-dom';
import './App.css';
import RepoPage from './components/RepoPage';
import ScrollToTop from './components/ScrollToTop';


function App() {
  return (
    <Router>
    <div className="App">
    <h1>Want to see other people's projects? Enter a Github username and Voila!</h1>
    <ScrollToTop />
    <Switch>
      <Route>
      <RepoPage />
      </Route>
     </Switch>
    </div>
    </Router>
  );
}

export default App;

Snippet of my Repo.js component

import React, {useEffect, useState} from 'react';
import axios from 'axios';
import RepoDetails from './RepoDetails';
import ScrollToTop from './ScrollToTop';
import '../App.css'

    function renderRows(repo) {
        return(
            <div 
                className='repo-button' 
                onClick={() => getDetails(repo.name)}
                key={repo.id}
            >
                <h3 className='repo-name'>
                {repo.name}
                <button onCLick={<ScrollToTop />}>View Repo</button>
                </h3>
            </div>

        )
    }

CodePudding user response:

There might be some misunderstanding with how ScrollToTop function component is used. I think when used in the App component, it is meant to automatically scroll to the top when the pathname changes. We can probably add this similar behavior for when the View Repo button is clicked by passing a callback function to onClick like () => window.scrollTo(0, 0) instead of the function component.

CodePudding user response:

Not to worry I've fixed the issue, I've set the window scroll to the top within the button onClick tag. Thanks anyway

  • Related