Search code examples
javascriptreactjshookrouter

Clicking on link changes route but not Component itself - React Hook Router


I'm facing the ReactJS routing issue. Working Demo. I'm using the hookrouter package.

Issue:

As mentioned in the demo, if I'm on the /users route and when I click on about link, the URL changes but About Component is not getting loaded.

What I want?

Is there a way to load a Component when I click on its link?

import { A, useRoutes } from "hookrouter";

const Users = () => {
  return (
    <div>
      <h1>Users</h1>
      <A href="/about">About</A>
    </div>
  );
};

const About = () => {
  return (
    <div>
      <h1>About</h1>
      <A href="/users">Users</A>
    </div>
  );
};

const routes = {
  "/users": () => <Users />,
  "/about": () => <About />
};

function App() {
  const routeResult = useRoutes(routes);
  return (
    <div className="App">
      <div>
        <A href="/users">Users Page</A>
      </div>
      <div>
        <A href="/about">About Page</A>
      </div>
      {routeResult}
    </div>
  );
}

const rootElement = document.getElementById("root");
ReactDOM.render(<React.StrictMode><App /></React.StrictMode>, rootElement);

Solution

  • There is an open issue in hookrouter library where if you wrap your app with <React.StrictMode> the navigations doesn't work.

    So, for now, remove the strict mode and you will be fine.

    index.js

    import React from "react";
    import ReactDOM from "react-dom";
    
    import App from "./App";
    
    const rootElement = document.getElementById("root");
    ReactDOM.render(
      // <React.StrictMode> // <------ comment this for now.
      <App />,
      // </React.StrictMode>,
      rootElement
    );
    

    working copy of your codesandbox