In my React app, I'm trying to navigate to a section of my first page when pressing a button on my Nav Bar. I'm achieving this with an onClick function on my button:
const onNavClick = (e, id) => {
let element = document.getElementById(id);
e.preventDefault();
element.scrollIntoView();
};
...
<Button
onClick={(e) => onNavClick(e, "products")}
...
>
Shop
</Button>
I'm also specifying an id on the element I want to navigate to.
Everything works as expected in the main page since that element is already in the DOM. The issue is that I can't access it when I go to another page and press the Nav button to get to that part. I'm getting this error:
Cannot read properties of null (reading 'scrollIntoView')
Is there any way I can access that element from other pages and navigate to that section in my first page?
You cannot scroll to an element that doesn't exist on the page. See the docs.
The Element interface's scrollIntoView() method scrolls the element's parent container such that the element on which scrollIntoView() is called is visible to the user.
If you want to navigate between pages, there are various options.
You can use a Link component from MUI:
<Link href='#'>Link to somewhere</Link>
If you're using Next.js, you can use their built-in router:
import { useRouter } from 'next/router'
const router = useRouter()
router.push('/homepage')
Another commonly-used router is react-router:
import { useNavigate } from "react-router-dom"
let navigate = useNavigate()
navigate('/homepage')
If you want to navigate to the page and then scroll to the element, you can pass some kind of data to indicate this, and then handle it in the destination page.
Example using Next.js:
Pass data as a query:
import { useRouter } from 'next/router'
const router = useRouter()
// Pass some kind of reference to the element you want to scroll to
router.push({
pathname: '/homepage',
query: { scrollTo: element }
})
In /pages/homepage, check the query and handle appropriately:
import { useRouter } from 'next/router'
const router = useRouter()
let element
if (router.query?.scrollTo)
{
element = router.query.scrollTo
// Now scroll to the element
}