Search code examples
javascriptreactjsreact-router-dom

Page refreshing


I am working on a product website with React and each time I click on a particular menu, it refreshes my entire page instead of just rendering component.

export const Header = () => {
  return (
    <header>
      <a href="/" className="logo">
        <img src={Logo} alt="Logo" />
        <span>Taskify</span>
      </a>
      <nav className="navigation">
        <a href="/" className="link">Home</a>
        <a href="/products" className="link">Products</a>
        <a href="/contact" className="link">Contact</a>
      </nav>
    </header>
  )
}

How do I get this fix, it's kinda slowing down my app.


Solution

  • The code you are using is rendering raw anchor tags, which when clicked will make a page request to the server and reload the page.

    If you are using React-Router-DOM to handle client-side routing and navigation, then import and use the Link component instead. This component intercepts the request and updates the view client-side and avoids reloading the page.

    import { Link } from 'react-router-dom';
    
    export const Header = () => {
      return (
        <header>
          <Link to="/" className="logo">
            <img src={Logo} alt="Logo" />
            <span>Taskify</span>
          </Link>
          <nav className="navigation">
            <Link to="/" className="link">Home</Link>
            <Link to="/products" className="link">Products</Link>
            <Link to="/contact" className="link">Contact</Link>
          </nav>
        </header>
      );
    };