DEV Community

Agam
Agam

Posted on • Edited on

React Hooks, Routing with a Layout

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


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 }) {
    useTitle(title);
    return (
        <div className="flex flex-col items-strech">
            <header className="w-full bg-blue-100 text-center">
                This is my header - {title}
            </header>
            <main className="w-full bg-blue-300 text-center">
                {children}
            </main>
            <footer className="w-full bg-blue-600 text-center">
                This is my footer.
            </footer>
        </div>
    );
}
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 {
    HomePage,
    AboutPage,
    NotFoundPage
}
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

Top comments (0)