DEV Community

Agam
Agam

Posted on • Edited on

2 1

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

Sentry image

Hands-on debugging session: instrument, monitor, and fix

Join Lazar for a hands-on session where you’ll build it, break it, debug it, and fix it. You’ll set up Sentry, track errors, use Session Replay and Tracing, and leverage some good ol’ AI to find and fix issues fast.

RSVP here →

Top comments (0)

A Workflow Copilot. Tailored to You.

Pieces.app image

Our desktop app, with its intelligent copilot, streamlines coding by generating snippets, extracting code from screenshots, and accelerating problem-solving.

Read the docs