I'm following the second answer to implement a scroll to top every time there's a route change. The answer suggests creating a new component, <ScrollToTop />
, which I did
import { useEffect } from 'react';
import { withRouter } from 'react-router-dom';
function ScrollToTop({ history }) {
useEffect(() => {
const unlisten = history.listen(() => {
window.scrollTo(0, 0);
});
return () => {
unlisten();
}
}, []);
return (null);
}
export default withRouter(ScrollToTop);
I'm confused as to where to place such component, since my app is structured a bit differently. See the index.js
and App.js
files below.
index.js
ReactDOM.render(
<>
<EWLoader />
<ContextProvider>
<Router> //tried placing below <Router>, didn't work
<App />
</Router>
</ContextProvider>
</>,
document.getElementById('root'),
)
App.js
function App() {
return (
<> //tried placing above <Switch>, didn't work
<Switch>
<Route path="/EWadmin">
<Admin />
</Route>
<Route path="/ewadmin-allbookings">
<AdminAllBookings />
</Route>
<Route path="/">
<EWHeader />
<Middleware />
{/* <EWPopular /> */}
</Route>
</Switch>
</>
)
}
I've also noticed <ScrollToTop />
is destructuring an object's property history
but I'm not importing or declaring it anywhere in index.js
or App.js
. Perhaps something should be done with regards to that?