DEV Community

Cover image for Setup Nextjs Tailwind CSS Styled Components with TypeScript
Mohammad Abu Mattar
Mohammad Abu Mattar

Posted on

Setup Nextjs Tailwind CSS Styled Components with TypeScript

Introduction

In this post, we will setup Nextjs Tailwind CSS Styled Components with TypeScript, and we will use the following tools:

  • Nextjs
  • Tailwind CSS
  • Styled Components
  • TypeScript

Prerequisites

You need to have the following tools installed on your system:

  • Node.js
  • Yarn

Setup Nextjs App

Step 1: Create a Nextjs app

First, we will create a Nextjs app using the following command:

# Create a Nextjs app
yarn create next-app nextjs-tailwind-styled-components-typescript
Enter fullscreen mode Exit fullscreen mode

Then, you will be asked to choose a TypeScript and ESLint, choose the following options:

# Choose a TypeScript
✔ Would you like to use TypeScript with this project? … No / Yes # Choose Yes

# Choose a ESLint
✔ Would you like to use ESLint with this project? … No / Yes # Choose Yes
Enter fullscreen mode Exit fullscreen mode

Step 2: Go to the Nextjs app directory

After creating the Nextjs app, we need to go to the Nextjs app directory using the following command:

# Go to the Nextjs app directory
cd nextjs-tailwind-styled-components-typescript
Enter fullscreen mode Exit fullscreen mode

Step 3: Prepare the Nextjs app

First, we need to install the following dependencies:

# Install the following dependencies
yarn add -D eslint-config-prettier eslint-plugin-prettier prettier
Enter fullscreen mode Exit fullscreen mode

Next, we need to create a .npmrc file in the root directory of the Nextjs app, and we will add the following content to the .npmrc file:

# Create a .npmrc file
touch .npmrc
Enter fullscreen mode Exit fullscreen mode
# Add the following content to the .npmrc file
shamefully-hoist=true
engine-strict=true
save-exact = true
tag-version-prefix=""
strict-peer-dependencies = false
auto-install-peers = true
lockfile = true
Enter fullscreen mode Exit fullscreen mode

After, we need to create a .nvmrc file in the root directory of the Nextjs app, and we will add the following content to the .nvmrc file:

# Create a .nvmrc file
touch .nvmrc
Enter fullscreen mode Exit fullscreen mode
# Add the following content to the .nvmrc file
lts/fermium
Enter fullscreen mode Exit fullscreen mode

Then, we need to create a .yarnrc file in the root directory of the Nextjs app, and we will add the following content to the .yarnrc file:

# Create a .yarnrc file
touch .yarnrc
Enter fullscreen mode Exit fullscreen mode
# Add the following content to the .yarnrc file
--install.ignore-engines true
Enter fullscreen mode Exit fullscreen mode

Then, we need to create a .prettierrc file in the root directory of the Nextjs app, and we will add the following content to the .prettierrc file:

# Create a .prettierrc file
touch .prettierrc
Enter fullscreen mode Exit fullscreen mode
# Add the following content to the .prettierrc file
{
  "printWidth": 80,
  "tabWidth": 2,
  "useTabs": false,
  "semi": true,
  "singleQuote": true,
  "quoteProps": "as-needed",
  "jsxSingleQuote": false,
  "trailingComma": "es5",
  "bracketSpacing": true,
  "jsxBracketSameLine": false,
  "arrowParens": "always",
  "requirePragma": false,
  "insertPragma": false,
  "proseWrap": "preserve",
  "htmlWhitespaceSensitivity": "css",
  "endOfLine": "lf"
}
Enter fullscreen mode Exit fullscreen mode

Then, we need to create a .prettierignore file in the root directory of the Nextjs app, and we will add the following content to the .prettierignore file:

# Create a .prettierignore file
touch .prettierignore
Enter fullscreen mode Exit fullscreen mode
# Add the following content to the .prettierignore file
.yarn
.vscode
.next
dist
node_modules
Enter fullscreen mode Exit fullscreen mode

Then, we need to create a .eslintrc file in the root directory of the Nextjs app, and we will add the following content to the .eslintrc file:

# Create a .eslintrc file
touch .eslintrc
Enter fullscreen mode Exit fullscreen mode
# Add the following content to the .eslintrc file
{
  "extends": ["next", "next/core-web-vitals", "plugin:prettier/recommended"],
  "rules": {
    "prettier/prettier": ["error", {}, { "usePrettierrc": true }]
  }
}
Enter fullscreen mode Exit fullscreen mode

Then, we need to create a .eslintignore file in the root directory of the Nextjs app, and we will add the following content to the .eslintignore file:

# Create a .eslintignore file
touch .eslintignore
Enter fullscreen mode Exit fullscreen mode
# Add the following content to the .eslintignore file
.yarn
.vscode
.next
dist
node_modules
Enter fullscreen mode Exit fullscreen mode

Add, the engines field to the package.json file, and we will add the following content to the package.json file:

# Add the following content to the package.json file
{
  "engines": {
    "node": ">=16.0.0",
    "yarn": ">=1.22.0",
    "npm": "please-use-yarn"
  },
}
Enter fullscreen mode Exit fullscreen mode

Step 4: Install Tailwind CSS

First, we will install Tailwind CSS using the following command:

# Install Tailwind CSS
yarn add -D tailwindcss@latest postcss@latest autoprefixer@latest
Enter fullscreen mode Exit fullscreen mode

Then, we will create a Tailwind CSS configuration file using the following command:

# Create a Tailwind CSS configuration file
npx tailwindcss init -p
Enter fullscreen mode Exit fullscreen mode

After, we will change the tailwind.config.js file, and we will add the following content to the tailwind.config.js file:

// Add the following content to the tailwind.config.js file
/** @type {import('tailwindcss').Config} */

module.exports = {
  content: ['./src/**/*.{js,ts,jsx,tsx}'],
  theme: {
    extend: {},
  },
  plugins: [],
};
Enter fullscreen mode Exit fullscreen mode

Step 5: Install Styled Components

First, we will install Styled Components using the following command:

# Install Styled Components
yarn add styled-components

# Install Styled Components TypeScript
yarn add -D @types/styled-components

# Install Styled Components Babel Plugin
yarn add -D babel-plugin-styled-components
Enter fullscreen mode Exit fullscreen mode

Then, we will create a .babelrc file in the root directory of the Nextjs app using the following command:

# Create a .babelrc file
touch .babelrc
Enter fullscreen mode Exit fullscreen mode

Then, we will add the following code to the .babelrc file:

{
  "presets": ["next/babel"],
  "plugins": [
    [
      "styled-components",
      {
        "ssr": true,
        "displayName": true,
        "preprocess": false
      }
    ]
  ]
}
Enter fullscreen mode Exit fullscreen mode

Step 6: Install and Setup twin.macro

First, we will install twin.macro using the following command:

# Install twin.macro
yarn add twin.macro

# Install twin.macro Babel Plugin
yarn add -D babel-plugin-twin
Enter fullscreen mode Exit fullscreen mode

Then, we will add the following code to the .babelrc file:

{
  "presets": ["next/babel"],
  "plugins": [
    [
      "styled-components",
      {
        "ssr": true,
        "displayName": true,
        "preprocess": false
      }
    ],
    [
      "babel-plugin-twin",
      {
        "debug": false,
        "styled": "styled-components"
      }
    ],
    "babel-plugin-macros"
  ]
}
Enter fullscreen mode Exit fullscreen mode

Add, the babelMacros field to the package.json file, and we will add the following content to the package.json file:

# Add the following content to the package.json file
{
  "babelMacros": {
    "twin": {
      "styled": {
        "import": "default",
        "from": "styled-components"
      }
    }
  }
}
Enter fullscreen mode Exit fullscreen mode

Step 7: Setup _document.tsx

First, we will create a pages/_document.tsx file using the following command:

# Create a pages/_document.tsx file
touch pages/_document.tsx
Enter fullscreen mode Exit fullscreen mode

Then, we will add the following code to the pages/_document.tsx file:

import Document, {
  DocumentContext,
  Head,
  Html,
  Main,
  NextScript,
} from 'next/document';
import { ServerStyleSheet } from 'styled-components';

export default class _Document extends Document {
  static async getInitialProps(ctx: DocumentContext) {
    const sheet = new ServerStyleSheet();
    const originalRenderPage = ctx.renderPage;

    try {
      ctx.renderPage = () =>
        originalRenderPage({
          enhanceApp: (App) => (props) =>
            sheet.collectStyles(<App {...props} />),
        });

      const initialProps = await Document.getInitialProps(ctx);
      return {
        ...initialProps,
        styles: (
          <>
            {initialProps.styles}
            {sheet.getStyleElement()}
          </>
        ),
      };
    } finally {
      sheet.seal();
    }
  }

  render() {
    return (
      <Html>
        <Head>
          <meta name="theme-color" content="#000000" />
        </Head>
        <body>
          <Main />
          <NextScript />
        </body>
      </Html>
    );
  }
}
Enter fullscreen mode Exit fullscreen mode

Step 8: Setup _app.tsx

We will add the following code to the pages/_app.tsx file:

import type { AppProps } from 'next/app';
import Head from 'next/head';

import 'tailwindcss/tailwind.css';

const _App = ({ Component, pageProps }: AppProps) => {
  return (
    <>
      <Head>
        <meta name="viewport" content="width=device-width, initial-scale=1" />
        <title>Create Next App</title>
        <meta name="description" content="Generated by create next app" />
        <link rel="icon" href="/favicon.ico" />
      </Head>
      <Component {...pageProps} />;
    </>
  );
};

export default _App;
Enter fullscreen mode Exit fullscreen mode

Step 9: Start styling

We will create a styles directory in the root directory of the Nextjs app using the following command:

# Create a styles directory
mkdir styles
Enter fullscreen mode Exit fullscreen mode

Then, we will create a main.ts file in the styles directory using the following command:

# Create a styles/main.ts file
touch styles/main.ts
Enter fullscreen mode Exit fullscreen mode

Then, we will add the following code to the styles/main.ts file:

import styled from 'styled-components';
import tw from 'twin.macro';

export const Container = tw.div`
  flex
  min-h-screen
  flex-col
  items-center
  justify-center
  py-2
`;

export const Main = tw.main`
  flex
  w-full
  flex-1
  flex-col
  items-center
  justify-center
  px-20
  text-center
`;

export const Title = tw.h1`
  text-6xl
  font-bold
`;

export const TitleLink = tw.a`
  text-blue-600
`;

export const Description = tw.p`
  mt-3
  text-2xl
`;

export const DescriptionCodeHighlight = tw.code`
  rounded-md
  bg-gray-100
  p-3
  font-mono 
  text-lg
`;

export const Cards = tw.div`
  mt-6 flex
  max-w-4xl
  flex-wrap
  items-center
  justify-around
  sm:w-full
`;

export const Card = tw.a`
  mt-6
  w-96
  rounded-xl
  border
  p-6
  text-left
  hover:text-blue-600
  focus:text-blue-600
`;

export const CardTitle = tw.h3`
  text-2xl
  font-bold
`;

export const CardDescription = tw.p`
  mt-4
  text-xl
`;

export const Footer = tw.footer`
  flex
  h-24
  w-full
  items-center
  justify-center
  border-t
`;

export const FooterCopyRight = tw.a`
  flex
  items-center
  justify-center
  gap-2
`;
Enter fullscreen mode Exit fullscreen mode

Then, we will redisign the pages/index.tsx file using the following code:

import type { NextPage } from 'next';
import Image from 'next/image';

import {
  Container,
  Main,
  Title,
  TitleLink,
  Description,
  DescriptionCodeHighlight,
  Cards,
  Card,
  CardTitle,
  Footer,
  FooterCopyRight,
} from '../styles/Home.styles';

const HomePage: NextPage = () => {
  return (
    <Container>
      <Main>
        <Title>
          Welcome to <TitleLink href="https://nextjs.org">Next.js!</TitleLink>
        </Title>

        <Description>
          Get started by editing{' '}
          <DescriptionCodeHighlight>pages/index.tsx</DescriptionCodeHighlight>
        </Description>

        <Cards>
          <Card href="https://nextjs.org/docs">
            <CardTitle>Documentation &rarr;</CardTitle>
            <p>Find in-depth information about Next.js features and API.</p>
          </Card>

          <Card href="https://nextjs.org/learn">
            <CardTitle>Learn &rarr;</CardTitle>
            <p>Learn about Next.js in an interactive course with quizzes!</p>
          </Card>

          <Card href="https://github.com/vercel/next.js/tree/canary/examples">
            <CardTitle>Examples &rarr;</CardTitle>
            <p>Discover and deploy boilerplate example Next.js projects.</p>
          </Card>

          <Card
            href="https://vercel.com/new?utm_source=create-next-app&utm_medium=default-template&utm_campaign=create-next-app"
            target="_blank"
            rel="noopener noreferrer"
          >
            <h2>Deploy &rarr;</h2>
            <p>
              Instantly deploy your Next.js site to a public URL with Vercel.
            </p>
          </Card>
        </Cards>
      </Main>

      <Footer>
        <FooterCopyRight
          href="https://vercel.com?utm_source=create-next-app&utm_medium=default-template&utm_campaign=create-next-app"
          target="_blank"
          rel="noopener noreferrer"
        >
          Powered by{' '}
          <Image src="/vercel.svg" alt="Vercel Logo" width={72} height={16} />
        </FooterCopyRight>
      </Footer>
    </Container>
  );
};

export default HomePage;
Enter fullscreen mode Exit fullscreen mode

Source Code

The source code for this tutorial is available on GitHub

Live Demo

The live demo for this tutorial is available on Vercel

Conclusion

In this tutorial, we have learned how to use Tailwind CSS with Nextjs and Styled Components. We have also learned how to use TypeScript with Nextjs and Styled Components.

References

Top comments (0)