Tautan khusus bereaksi

//Simple example
import { Link, LinkProps, useMatch, NavLink, useResolvedPath } from "react-router-dom";//v6.0

export const CustomLink = ({ children, to, ...props }: LinkProps) => {
  let resolved = useResolvedPath(to);
  let match = useMatch({ path: resolved.pathname, end: true });

  return (
    <div>
      <Link className={match ? "nav-active" : ""} {...props} to={resolved.pathname}>
        {children}
      </Link>
    </div>
  );
};


// How to use here
import { CustomLink } from "./components/CustomLink";

  function App() {
    return (
      <>
        <div className="main-layout">
          <nav>
            <img src={logo} alt="Logo" />

            <ul>
              <li>
                <CustomLink to="/">Home</CustomLink>
              </li>
              <li>
                <CustomLink to="/about">About</CustomLink>
              </li>
              <li>
                <CustomLink to="/users">Users</CustomLink>
              </li>
            </ul>
          </nav>

          <Routes>
            <Route path="/about" element={<h1>About Page</h1>} />
            <Route path="/users" element={<h1>Users Page</h1>} />
            <Route path="/" element={<h1>Home Page</h1>} />

            <Route path="/*" element={<Navigate to="/" replace />} />
          </Routes>
        </div>
      </>
    );
}


//Or more Simple

function App() {
  return (
    <>
      <div className="main-layout">
        <nav>
          <img src={logo} alt="Logo" />
          <ul>
            <li>
              <NavLink className={({ isActive }) => (isActive ? "nav-active" : "")}
                to="/users"
              >
                Users
              </NavLink>
            </li>
          </ul>
        </nav>

        <Routes>
          <Route path="/users" element={<h1>Users Page</h1>} />
          <Route path="/*" element={<Navigate to="/" replace />} />
        </Routes>
      </div>
    </>
  );
}


Ángel De La Cruz