I have a Navbar with the routes set up like this:
import '../styles/Nav.css'
import { BrowserRouter as Router, Routes, Route, Link} from 'react-router-dom'
import { Home } from '../components/Home'
import { Contact } from '../components/Contact'
import { Error } from '../components/Error'
export const Navbar = () => {
return (
<>
<Router>
{/* Nav Links */}
<div className='nav-major-container'>
<div className='logo-container'>
<p>Logo h</p>
</div>
<nav className='nav-container'>
<Link to='/' className='home-link'>Home</Link>
<Link to='/contact' className='contact-link'>Contact</Link>
</nav>
</div>
<Routes>
<Route path='/' element={<Home/>}/>
<Route path='/contact' element={<Contact/>}/>
{/* Error Route */}
<Route path='*' element={<Error/>}/>
</Routes>
</Router>
</>
)
}
I want to be able to click the links and be redirected to a part of the page with the component, similar to the a href
in html. For example, when I click the Contact component, I want to be redirected to the part of the page with the Contact.jsx
As shown above, setting up the routes only made it so that when I click any of the links in the navbar, it displays the component on the page. This is not what I want.
2
Answers
I haven’t done nothing with
react-router
for a while now, i’d assume you can put the id of the html-element in hashtag#
insideto
-tag inLink
-component just like the way you do it with thea
-tag:I’m not sure if it’ll work. But if not, please take a look here
You can use useRef() hook.
For example,
After you click this button or link, add onClick function.