DEV Community


React Hooks, Routing with a Layout

agamm profile image Agam ・2 min read

Let's create a consistent layout for our react hook routing project.

If you want the basic routing from the last tutorial head here: React Hooks with Routing the Easy way

If there is a better way of achieving this with Paratron/hookrouter, please let me know in the comments.

Create a layout

I'm using tailwind2, you can do it too here.

import {useTitle} from 'hookrouter';
function Layout({ children, title }) {
    return (
        <div className="flex flex-col items-strech">
            <header className="w-full bg-blue-100 text-center">
                This is my header - {title}
            <main className="w-full bg-blue-300 text-center">
            <footer className="w-full bg-blue-600 text-center">
                This is my footer.
export default Layout;
Enter fullscreen mode Exit fullscreen mode

Bonus: Let's make it nicer to import pages

Move all of your pages to a new directory named pages. There create an index.js file:

import HomePage from './HomePage';
import AboutPage from './AboutPage';
import NotFoundPage from './NotFoundPage';

export {
Enter fullscreen mode Exit fullscreen mode

Let's import and use it in App.js

import './App.css';
import {useRoutes} from 'hookrouter';
import Layout from './Layout';

// Pages - This is the previous bonus
import {HomePage, AboutPage, NotFoundPage} from './pages/';

// This applies our layout
function withLayout(page, title){
  return <Layout title={title}>{page}</Layout>

const routes = {
  '/': () => withLayout(<HomePage />, "Home"),
  '/about': () => withLayout(<AboutPage />, "About"),

function App() {
  const routeResult = useRoutes(routes);
  return routeResult || withLayout(<NotFoundPage />, "Not found!");

export default App;

Enter fullscreen mode Exit fullscreen mode

It should look something like:
Alt Text

Discussion (0)

Editor guide