Summary
This is a react hook that allows you to navigate to a specific section of a page by scrolling to it.
visit npmjs1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
import useScrollNavigate from 'react-use-scroll-navigate'; const App = () => { const { scrollNavigateError, scrollNavigate } = useScrollNavigate(); return ( <div> <button onClick={ ()=> { scrollNavigate('/'); //It will navigate & scroll to the top ! }}> Go to homepage! </button> </div> ); };
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34
//Main app createRoot(document.getElementById("root")).render( <StrictMode> <BrowserRouter> <NavigateContextProvider> {/*Ref navigation scroll navigation works with context*/} <App /> </NavigateContextProvider> </BrowserRouter> </StrictMode> ) //On one page export default () => { const { navigateToRef } = useNavigateContext(); return ( <Fragment> <h1>About</h1> <button onClick={() => navigateToRef("/")}>Home</button> </Fragment> ) } // On another page export default () => { const { navigationRef } = useNavigateContext(); return ( <Fragment> <h1>Home</h1> <div ref={navigationRef} /> </Fragment> ) }
Made with ❤️ by Alexandre BAUDRY