I am attempting to get the most basic example of hookrouter (an alternative routing library to react-router-dom) working and cannot get the page to change. The URL address will change to /about when I click on the /about link but the UI doesn't update. I am using it with a brand new create-react-app project. I tried the same project on StackBlitz and noticed that after installing hookrouter it said there was a package/dependency missing for the 'url' library....which is interesting because the url package isn't a dependency of hookrouter. But the second I installed the url package on StackBlitz.io, the links worked and the UI updated appropriately when the url changed. I tried installing the url library on my local create-react-app project and it did not fix the situation. So I am not sure if there is a missing dependency, but I can see the useRoutes hook actually loading a change when the URL changes but for whatever reason the UI will not update. Here is my code for my App.js file.
import { A, useRoutes } from 'hookrouter';
import React from 'react';
import './App.css';
import { AboutPage } from './pages/AboutPage';
import { HomePage } from './pages/HomePage';
const routes = {
'/': () => <HomePage />,
'/about': () => <AboutPage />
}
function App() {
const routeResult = useRoutes(routes);
return (
<div className="App">
<A href="/">Home</A>
<A href="/about">About</A>
<header className="App-header">
{routeResult}
</header>
</div>
);
}
export default App;
1. useHistory: This is one of the most popular hooks provided by React Router. It lets you access the history instance used by React Router. Using the history instance you can redirect users to another page.
React Router has an higher-order component called withRouter with which we can pass in the React Router's history, location, and match objects to our React components as props. To use withRouter , you should wrap your App component inside withRouter() as a parameter.
useParams returns an object of key/value pairs of URL parameters. Use it to access match. params of the current <Route> .
With the release of React Router v6, the Redirect component was removed and replaced with the Navigate component, which operates just as the Redirect component does by taking in the to prop to enable you redirect to the page you specify.
It seems that hookrouter
doesn't work with Strict Mode that comes enabled by default in the latest versions of CRA. (same I guess with StackBlitz and codesandbox)
You'll need to just remove the <React.StrictMode>
component from your index.js
<React.StrictMode>
<App />
</React.StrictMode>
codesandbox emaple
With that said, Unless you have really simple App, I encourage you to use react-router-dom
as this package is relatively new and you may have more unusual bugs.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With