Type something to search...
Setup Nextjs Tailwind CSS Styled Components with TypeScript

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:

Terminal window
# Create a Nextjs app
yarn create next-app nextjs-tailwind-styled-components-typescript

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

Terminal window
# 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

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:

Terminal window
# Go to the Nextjs app directory
cd nextjs-tailwind-styled-components-typescript

Step 3: Prepare the Nextjs app

First, we need to install the following dependencies:

Terminal window
# Install the following dependencies
yarn add -D eslint-config-prettier eslint-plugin-prettier prettier

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:

Terminal window
# Create a .npmrc file
touch .npmrc
1
# Add the following content to the .npmrc file
2
shamefully-hoist=true
3
engine-strict=true
4
save-exact = true
5
tag-version-prefix=""
6
strict-peer-dependencies = false
7
auto-install-peers = true
8
lockfile = true

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:

Terminal window
# Create a .nvmrc file
touch .nvmrc
1
# Add the following content to the .nvmrc file
2
lts/fermium

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:

Terminal window
# Create a .yarnrc file
touch .yarnrc
1
# Add the following content to the .yarnrc file
2
--install.ignore-engines true

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:

Terminal window
# Create a .prettierrc file
touch .prettierrc
1
# Add the following content to the .prettierrc file
2
{
3
"printWidth": 80,
4
"tabWidth": 2,
5
"useTabs": false,
6
"semi": true,
7
"singleQuote": true,
8
"quoteProps": "as-needed",
9
"jsxSingleQuote": false,
10
"trailingComma": "es5",
11
"bracketSpacing": true,
12
"jsxBracketSameLine": false,
13
"arrowParens": "always",
14
"requirePragma": false,
15
"insertPragma": false,
16
"proseWrap": "preserve",
17
"htmlWhitespaceSensitivity": "css",
18
"endOfLine": "lf"
19
}

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:

Terminal window
# Create a .prettierignore file
touch .prettierignore
1
# Add the following content to the .prettierignore file
2
.yarn
3
.vscode
4
.next
5
dist
6
node_modules

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:

Terminal window
# Create a .eslintrc file
touch .eslintrc
1
# Add the following content to the .eslintrc file
2
{
3
"extends": ["next", "next/core-web-vitals", "plugin:prettier/recommended"],
4
"rules": {
5
"prettier/prettier": ["error", {}, { "usePrettierrc": true }]
6
}
7
}

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:

Terminal window
# Create a .eslintignore file
touch .eslintignore
1
# Add the following content to the .eslintignore file
2
.yarn
3
.vscode
4
.next
5
dist
6
node_modules

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

1
# Add the following content to the package.json file
2
{
3
"engines": {
4
"node": ">=16.0.0",
5
"yarn": ">=1.22.0",
6
"npm": "please-use-yarn"
7
},
8
}

Step 4: Install Tailwind CSS

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

Terminal window
# Install Tailwind CSS
yarn add -D tailwindcss@latest postcss@latest autoprefixer@latest

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

Terminal window
# Create a Tailwind CSS configuration file
npx tailwindcss init -p

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

1
// Add the following content to the tailwind.config.js file
2
/** @type {import('tailwindcss').Config} */
3
4
module.exports = {
5
content: ['./src/**/*.{js,ts,jsx,tsx}'],
6
theme: {
7
extend: {},
8
},
9
plugins: [],
10
};

Step 5: Install Styled Components

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

Terminal window
# 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

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

Terminal window
# Create a .babelrc file
touch .babelrc

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

1
{
2
"presets": ["next/babel"],
3
"plugins": [
4
[
5
"styled-components",
6
{
7
"ssr": true,
8
"displayName": true,
9
"preprocess": false
10
}
11
]
12
]
13
}

Step 6: Install and Setup twin.macro

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

Terminal window
# Install twin.macro
yarn add twin.macro
# Install twin.macro Babel Plugin
yarn add -D babel-plugin-twin

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

1
{
2
"presets": ["next/babel"],
3
"plugins": [
4
[
5
"styled-components",
6
{
7
"ssr": true,
8
"displayName": true,
9
"preprocess": false
10
}
11
],
12
[
13
"babel-plugin-twin",
14
{
15
"debug": false,
16
"styled": "styled-components"
17
}
18
],
19
"babel-plugin-macros"
20
]
21
}

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

1
# Add the following content to the package.json file
2
{
3
"babelMacros": {
4
"twin": {
5
"styled": {
6
"import": "default",
7
"from": "styled-components"
8
}
9
}
10
}
11
}

Step 7: Setup _document.tsx

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

Terminal window
# Create a pages/_document.tsx file
touch pages/_document.tsx

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

1
import Document, {
2
DocumentContext,
3
Head,
4
Html,
5
Main,
6
NextScript,
7
} from 'next/document';
8
import {ServerStyleSheet} from 'styled-components';
9
10
export default class _Document extends Document {
11
static async getInitialProps(ctx: DocumentContext) {
12
const sheet = new ServerStyleSheet();
13
const originalRenderPage = ctx.renderPage;
14
15
try {
16
ctx.renderPage = () =>
17
originalRenderPage({
18
enhanceApp: (App) => (props) =>
19
sheet.collectStyles(<App {...props} />),
20
});
21
22
const initialProps = await Document.getInitialProps(ctx);
23
return {
24
...initialProps,
25
styles: (
26
<>
27
{initialProps.styles}
28
{sheet.getStyleElement()}
29
</>
30
),
31
};
32
} finally {
33
sheet.seal();
34
}
35
}
36
37
render() {
38
return (
39
<Html>
40
<Head>
41
<meta name="theme-color" content="#000000" />
42
</Head>
43
<body>
44
<Main />
45
<NextScript />
46
</body>
47
</Html>
48
);
49
}
50
}

Step 8: Setup _app.tsx

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

1
import type {AppProps} from 'next/app';
2
import Head from 'next/head';
3
4
import 'tailwindcss/tailwind.css';
5
6
const _App = ({Component, pageProps}: AppProps) => {
7
return (
8
<>
9
<Head>
10
<meta name="viewport" content="width=device-width, initial-scale=1" />
11
<title>Create Next App</title>
12
<meta name="description" content="Generated by create next app" />
13
<link rel="icon" href="/favicon.ico" />
14
</Head>
15
<Component {...pageProps} />;
16
</>
17
);
18
};
19
20
export default _App;

Step 9: Start styling

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

Terminal window
# Create a styles directory
mkdir styles

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

Terminal window
# Create a styles/main.ts file
touch styles/main.ts

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

1
import styled from 'styled-components';
2
import tw from 'twin.macro';
3
4
export const Container = tw.div`
5
flex
6
min-h-screen
7
flex-col
8
items-center
9
justify-center
10
py-2
11
`;
12
13
export const Main = tw.main`
14
flex
15
w-full
16
flex-1
17
flex-col
18
items-center
19
justify-center
20
px-20
21
text-center
22
`;
23
24
export const Title = tw.h1`
25
text-6xl
26
font-bold
27
`;
28
29
export const TitleLink = tw.a`
30
text-blue-600
31
`;
32
33
export const Description = tw.p`
34
mt-3
35
text-2xl
36
`;
37
38
export const DescriptionCodeHighlight = tw.code`
39
rounded-md
40
bg-gray-100
41
p-3
42
font-mono
43
text-lg
44
`;
45
46
export const Cards = tw.div`
47
mt-6 flex
48
max-w-4xl
49
flex-wrap
50
items-center
51
justify-around
52
sm:w-full
53
`;
54
55
export const Card = tw.a`
56
mt-6
57
w-96
58
rounded-xl
59
border
60
p-6
61
text-left
62
hover:text-blue-600
63
focus:text-blue-600
64
`;
65
66
export const CardTitle = tw.h3`
67
text-2xl
68
font-bold
69
`;
70
71
export const CardDescription = tw.p`
72
mt-4
73
text-xl
74
`;
75
76
export const Footer = tw.footer`
77
flex
78
h-24
79
w-full
80
items-center
81
justify-center
82
border-t
83
`;
84
85
export const FooterCopyRight = tw.a`
86
flex
87
items-center
88
justify-center
89
gap-2
90
`;

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

1
import type {NextPage} from 'next';
2
import Image from 'next/image';
3
4
import {
5
Container,
6
Main,
7
Title,
8
TitleLink,
9
Description,
10
DescriptionCodeHighlight,
11
Cards,
12
Card,
13
CardTitle,
14
Footer,
15
FooterCopyRight,
16
} from '../styles/Home.styles';
17
18
const HomePage: NextPage = () => {
19
return (
20
<Container>
21
<Main>
22
<Title>
23
Welcome to <TitleLink href="https://nextjs.org">Next.js!</TitleLink>
24
</Title>
25
26
<Description>
27
Get started by editing{' '}
28
<DescriptionCodeHighlight>pages/index.tsx</DescriptionCodeHighlight>
29
</Description>
30
31
<Cards>
32
<Card href="https://nextjs.org/docs">
33
<CardTitle>Documentation &rarr;</CardTitle>
34
<p>Find in-depth information about Next.js features and API.</p>
35
</Card>
36
37
<Card href="https://nextjs.org/learn">
38
<CardTitle>Learn &rarr;</CardTitle>
39
<p>Learn about Next.js in an interactive course with quizzes!</p>
40
</Card>
41
42
<Card href="https://github.com/vercel/next.js/tree/canary/examples">
43
<CardTitle>Examples &rarr;</CardTitle>
44
<p>Discover and deploy boilerplate example Next.js projects.</p>
45
</Card>
46
47
<Card
48
href="https://vercel.com/new?utm_source=create-next-app&utm_medium=default-template&utm_campaign=create-next-app"
49
target="_blank"
50
rel="noopener noreferrer"
51
>
52
<h2>Deploy &rarr;</h2>
53
<p>
54
Instantly deploy your Next.js site to a public URL with Vercel.
55
</p>
56
</Card>
57
</Cards>
58
</Main>
59
60
<Footer>
61
<FooterCopyRight
62
href="https://vercel.com?utm_source=create-next-app&utm_medium=default-template&utm_campaign=create-next-app"
63
target="_blank"
64
rel="noopener noreferrer"
65
>
66
Powered by{' '}
67
<Image src="/vercel.svg" alt="Vercel Logo" width={72} height={16} />
68
</FooterCopyRight>
69
</Footer>
70
</Container>
71
);
72
};
73
74
export default HomePage;

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

Related Posts

Check out some of our other posts

React With Redux Toolkit

React With Redux Toolkit

Prerequisites This post assumes that you have a basic understanding of React and Redux. and it will be better if you have some experience with React Hooks like useReducer. Introduction Now

read more
Building a Customizable Image Slider in React Using Hooks, SCSS, and TypeScript

Building a Customizable Image Slider in React Using Hooks, SCSS, and TypeScript

Introduction In this tutorial, we will be building a customizable image slider in React using hooks, SCSS, and TypeScript. An image slider is a common UI element used in web applications to displ

read more
Unlocking the Power of React Context API: Demystifying State Management

Unlocking the Power of React Context API: Demystifying State Management

Introduction In the ever-evolving realm of web development, the effective management of application state is a pivotal aspect that can either elevate or hinder your project's success. In this con

read more
Setting up JWT Authentication in Typescript with Express, MongoDB, Babel, Prettier, ESLint, and Husky: Part 2

Setting up JWT Authentication in Typescript with Express, MongoDB, Babel, Prettier, ESLint, and Husky: Part 2

Introduction Why do we even need an authentication mechanism in an application? in my opinion, it doesn't need to be explained. The phrases authentication and authorization have likely crossed yo

read more
Run TypeScript Without Compiling

Run TypeScript Without Compiling

Introduction In this post, I will show you how to run TypeScript without compiling it to JavaScript. This is useful for debugging and testing. In this post, I will show you how to do it. Setu

read more