(EDITED)
I have a react app where I want to have the navbar on every page. So I made a navbar component and added it to every new page. On the main page, the navbar works fine by scrolling to the selected section. However, on any other page, the navbar cannot scroll to that section because it's not found. So my question is, how do I make the navbar clickable to reroute to the main page THEN scroll to an element.
Here is the simplified code
Navbar Code
export default function navbar(){
return(
<div className="nav-container">
<nav>
<ul className="desktop-nav">
<li>
<a
className="link-logo"
onClick = {() => {scrollTo('landing-page')}}
/>
</li>
<li>
<a onClick = {() => {scrollTo('elem1')}}>elem1</a>
</li>
<li>
<a onClick = {() => {scrollTo('elem2')}}>elem2</a>
</li>
<li>
<a onClick = {() => {scrollTo('elem3')}}>elem3</a>
</li>
</ul>
</nav>
</div>
);
}
function scrollTo(elem){
document.getElementById(elem).scrollIntoView(true);
}
Main page code
export default function Home(){
return(
<div>
<div id = 'elem1'>elem1</div>
<div id = 'elem2'>elem2</div>
<div id = 'elem3'>elem3</div>
<a href = '/somewhere'> Go to Second Page </a>
</div>
);
}
App router
function App() {
return (
<Router>
<Switch>
<Route exact path = '/' component = {SITE} />
<Route exact path = '/somewhere' component = {SECOND_PAGE}/>
</Switch>
</Router>
);
}
export default App;
Now from SECOND_PAGE component which is displayed as a separate page, how can I make the navbar links go to SITE component and scroll to the specified link without adding anything to the URL. I don't want the users to be able to see my div IDs and classnames if possible. I want the URL to be static as I navigate through those two components.