Last active
June 7, 2020 21:53
-
-
Save joseederangojr/b7fea0952b65fa8f3144dbe152f919c4 to your computer and use it in GitHub Desktop.
Scrolling to anchor tags using React Hooks (React Router, also working without router library)
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import React from "react" | |
import {Link} from "react-router-dom" | |
import { useScrollToView } from "./useScrollToView" | |
export default function Anchor() { | |
useScrollToView() | |
return ( | |
<div> | |
<nav> | |
<Link to="#about">About using React Router</Link> | |
<a href="#about">About using html anchor tag</a> | |
</nav> | |
<div id="#about">About Page</div> | |
</div> | |
) | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import { useEffect } from "react" | |
import { useLocation } from "react-router-dom" | |
export function useScrollToView() { | |
const { hash } = useLocation(); | |
/** | |
if you dont react-router or any routing library | |
const { hash } = window.location | |
*/ | |
function scrollTo(hash) { | |
if(hash) { | |
const el = document.getElementById(el) | |
if(el) { | |
el.scrollIntoView({ end: 'block', behavior: 'smooth' }) | |
} | |
} | |
} | |
useEffect(() => { | |
scrollTo(hash) | |
}, []) | |
useEffect(() => { | |
scrollTo(hash) | |
}, [hash]) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment