Skip to content

Instantly share code, notes, and snippets.

@joseederangojr
Last active June 7, 2020 21:53
Show Gist options
  • Save joseederangojr/b7fea0952b65fa8f3144dbe152f919c4 to your computer and use it in GitHub Desktop.
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)
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>
)
}
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