skip to Main Content

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


  1. 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 # inside to-tag in Link-component just like the way you do it with the a-tag:

    <Link to="#target"> Go to target! </Link>
    

    I’m not sure if it’ll work. But if not, please take a look here

    Login or Signup to reply.
  2. You can use useRef() hook.

    For example,

    const contactRef = React.useRef();
    
    const navigate = useNavigate(); // for navigation
    

    After you click this button or link, add onClick function.

    const handleClickContact = () => {
      navigate("/contact");
      contactRef.current?.scrollIntoView({ behavior: 'smooth' })
    }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search