I am currently working on a React application and I want to implement a functionality where pressing a button on my Nav Bar will navigate to a specific section on the first page. To achieve this, I have created an onClick function for my button:
const onNavClick = (e, id) => {
let element = document.getElementById(id);
e.preventDefault();
element.scrollIntoView();
};
...
<Button
onClick={(e) => onNavClick(e, "products")}
...
>
Shop
</Button>
I have also assigned an id
to the element that I wish to navigate to.
While everything works as expected on the main page where the element is present in the DOM, I encounter an issue when trying to access it from another page using the Nav button. The error message I receive is:
Cannot read properties of null (reading 'scrollIntoView')
Is there a way for me to access that element from other pages and navigate to that specific section on my first page?