skip to Main Content

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.

2

Answers


  1. 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>
      );
    };
    
    Login or Signup to reply.
  2. The issue you’re encountering where clicking on a menu item refreshes the entire page instead of just rendering the component is due to the default behavior of anchor () tags with href attributes. When you use , it triggers a full page refresh or navigation to the specified URL.

    To prevent this behavior and have React handle navigation without refreshing the page, you should use React Router or similar client-side routing solutions

      npm install react-router-dom
    
    
      import React from 'react';
      import { NavLink } from 'react-router-dom';
      import Logo from '../path/to/your/logo'; // Replace with the actual path to your logo
    
    export const Header = () => {
      return (
        <header>
          <NavLink to="/" className="logo">
            <img src={Logo} alt="Logo" />
            <span>Taskify</span>
          </NavLink>
          <nav className="navigation">
            <NavLink exact to="/" className="link">Home</NavLink>
            <NavLink to="/products" className="link">Products</NavLink>
            <NavLink to="/contact" className="link">Contact</NavLink>
          </nav>
        </header>
      );
    };
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search