Blog>
Snippets

Dynamic Routing with Tailwind CSS Styled Components in Next.js

Demonstrate how to style dynamic route components in Next.js with Tailwind CSS, ensuring styles are applied correctly to pages generated at both build and run time.
import { useRouter } from 'next/router';
import { useEffect } from 'react';
import 'tailwindcss/tailwind.css';

const DynamicPage = () => {
  const router = useRouter();
  const { id } = router.query; // Get the dynamic part of the route

  useEffect(() => {
    // Perform actions when component is rendered, like data fetching based on id
  }, [id]);

  return (
    <div className='p-4 bg-gray-200'>
      {/* Tailwind CSS styling is applied here */}
      <h1 className='text-xl font-bold text-gray-800'>Dynamic Page: {id}</h1>
      {/* Insert the rest of your page components here and style them with Tailwind CSS classes */}
    </div>
  );
};

export default DynamicPage;
This is a Next.js dynamic page component that uses useRouter to access the dynamic segment of the URL, applies Tailwind CSS styles, and handles any side-effects with useEffect hook.
import { AppProps } from 'next/app';
import Head from 'next/head';
import 'tailwindcss/tailwind.css';

function MyApp({ Component, pageProps }: AppProps) {
  return (
    <>
      <Head>
        <title>My Next.js App</title>
        <meta name='viewport' content='initial-scale=1.0, width=device-width' />
      </Head>
      <Component {...pageProps} />
    </>
  );
}

export default MyApp;
This is the custom App component in Next.js, which includes global styles from Tailwind CSS. All individual pages and components will be wrapped by this component.
// pages/_document.js (create this file if it doesn't exist)
import Document, { Html, Head, Main, NextScript } from 'next/document';
class MyDocument extends Document {
  render() {
    return (
      <Html>
        <Head />
        <body>
          <Main />
          <NextScript />
        </body>
      </Html>
    );
  }
}

export default MyDocument;
This is the custom Document component in Next.js. It's used to augment the HTML markup and usually includes site-wide settings like custom font imports or setting the body class that can't be done in the custom App component.