(UPDATED)
I am working on a react app where I need to include the navbar on each page. To achieve this, I created a navbar component and added it to all new pages. The navbar functions correctly on the main page by scrolling to the selected section. However, on other pages, the navbar is unable to scroll to the section because it cannot find it. My query is how can I make the navbar clickable to redirect to the main page and then scroll to an element.
Below is the simplified code
Navbar Component 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 Component 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 Code
function App() {
return (
<Router>
<Switch>
<Route exact path='/' component={SITE} />
<Route exact path='/somewhere' component={SECOND_PAGE}/>
</Switch>
</Router>
);
}
export default App;
From the SECOND_PAGE component displayed as a separate page, how can I ensure that the navbar links redirect to the SITE component and scroll to the specified link without altering the URL? I aim to keep the URL static while navigating between these two components and prevent users from viewing my div IDs and class names if possible.