DEV Community

Agam
Agam

Posted on • Edited on

React Hooks with Routing the Easy way

If you are interested in developer trends you should check out my new newsletter at: unzip.dev


No need for react-router nowadays, let's use a more simplistic approach with Paratron/hookrouter.

Install

npm install hookrouter

Simple example

In app.js we can write

import {useRoutes} from 'hookrouter';
import HomePage from './HomePage';
import AboutPage from './AboutPage';

const routes = {
  '/': () => <HomePage />,
  '/about': () => <AboutPage />,
};

function App() {
  const routeResult = useRoutes(routes);
  return routeResult || <NotFoundPage />;
}

export default App;
Enter fullscreen mode Exit fullscreen mode

HomePage can look like:

import {A} from 'hookrouter';
function HomePage() {
    return (
        <div className="Home">
        Home Page
        Go to <a href="/about">About</a>.
        </div>
    );
}
export default HomePage;
Enter fullscreen mode Exit fullscreen mode

Layout

I've created another tutorial that explains how to structure a project with a layout - React Hooks, Routing with a Layout.

More examples:

Top comments (0)