Certainly! Building upon the refined architecture we've discussed, I'll guide you through setting up a highly reusable, maintainable, and scalable landing page template using Next.js, React Hooks, TypeScript, and Tailwind CSS. This implementation will prioritize clean code, best practices, and cross-platform compatibility.
1. Project Setup
1.1. Initialize the Next.js Project with TypeScript
First, create a new Next.js project with TypeScript support:
npx create-next-app@latest my-landing-page --typescript
cd my-landing-page
1.2. Install Required Dependencies
Install the necessary libraries and tools:
# Install Tailwind CSS and its dependencies
npm install -D tailwindcss postcss autoprefixer
npx tailwindcss init -p
# Install Framer Motion for animations
npm install framer-motion
# Install Zustand for state management
npm install zustand
# Install next-i18next for internationalization
npm install next-i18next react-i18next i18next
# Install ESLint and Prettier for code quality
npm install -D eslint prettier eslint-config-prettier eslint-plugin-react @typescript-eslint/parser @typescript-eslint/eslint-plugin
# Install Jest and React Testing Library for testing
npm install -D jest @testing-library/react @testing-library/jest-dom @types/jest ts-jest
# Install Storybook for UI component exploration
npx sb init --typescript
1.3. Configure Tailwind CSS
Update tailwind.config.js to include paths to all your components:
// tailwind.config.js
module.exports = {
content: [
"./pages/**/*.{js,ts,jsx,tsx}",
"./components/**/*.{js,ts,jsx,tsx}",
"./stories/**/*.{js,ts,jsx,tsx}",
],
theme: {
extend: {
colors: {
primary: '#ff6347', // Example primary color
secondary: '#ff4500', // Example secondary color
},
},
},
plugins: [],
};
Import Tailwind directives in styles/globals.css:
/* styles/globals.css */
@tailwind base;
@tailwind components;
@tailwind utilities;
/* Custom Global Styles (if any) */
body {
@apply bg-gray-100 text-gray-900;
}
2. Project Structure
Here's an organized project structure to maintain clarity and scalability:
my-landing-page/
├── components/
│ ├── Button/
│ │ ├── Button.tsx
│ │ └── Button.module.css
│ ├── Header/
│ │ ├── Header.tsx
│ │ └── Header.module.css
│ ├── Footer/
│ │ ├── Footer.tsx
│ │ └── Footer.module.css
│ ├── Hero/
│ │ ├── Hero.tsx
│ │ └── Hero.module.css
│ ├── Features/
│ │ └── Features.tsx
│ ├── Testimonials/
│ │ └── Testimonials.tsx
│ ├── CTA/
│ │ └── CTA.tsx
│ └── ...other reusable components
├── hooks/
│ └── useGlobalState.ts
├── pages/
│ ├── index.tsx
│ ├── _app.tsx
│ └── api/
│ └── ...serverless functions
├── public/
│ ├── images/
│ ├── icons/
│ └── fonts/
├── styles/
│ ├── globals.css
│ └── tailwind.config.js
├── stories/
│ └── Button.stories.tsx
├── types/
│ └── index.d.ts
├── utils/
│ ├── helperFunctions.ts
│ └── constants.ts
├── .eslintrc.js
├── .prettierrc
├── jest.config.js
├── tsconfig.json
├── next.config.js
├── package.json
├── README.md
└── ...other configuration files
3. Configuration Files
3.1. ESLint Configuration
Set up ESLint to enforce coding standards:
// .eslintrc.js
module.exports = {
parser: '@typescript-eslint/parser',
extends: [
'plugin:react/recommended',
'plugin:@typescript-eslint/recommended',
'prettier', // Integrates Prettier for code formatting
],
plugins: ['react', '@typescript-eslint'],
settings: {
react: {
version: 'detect', // Automatically detect React version
},
},
rules: {
// Customize your rules
'react/react-in-jsx-scope': 'off', // Next.js handles React import
'@typescript-eslint/explicit-module-boundary-types': 'off',
},
};
3.2. Prettier Configuration
Configure Prettier for consistent code formatting:
// .prettierrc
{
"semi": true,
"singleQuote": true,
"printWidth": 80,
"tabWidth": 2,
"trailingComma": "es5",
"endOfLine": "auto"
}
3.3. Jest Configuration
Set up Jest for testing:
// jest.config.js
module.exports = {
preset: 'ts-jest',
testEnvironment: 'jsdom',
setupFilesAfterEnv: ['<rootDir>/jest.setup.js'],
moduleNameMapper: {
'\\.(css|less|sass|scss)$': 'identity-obj-proxy', // Mock CSS modules
},
};
Create jest.setup.js for additional Jest configurations:
// jest.setup.js
import '@testing-library/jest-dom';
3.4. TypeScript Configuration
Ensure TypeScript is properly configured:
// tsconfig.json
{
"compilerOptions": {
"target": "es5",
"lib": ["dom", "dom.iterable", "esnext"],
"allowJs": true,
"skipLibCheck": true,
"esModuleInterop": true,
"allowSyntheticDefaultImports": true,
"strict": true, // Enable strict mode for type safety
"forceConsistentCasingInFileNames": true,
"noEmit": true,
"module": "esnext",
"moduleResolution": "node",
"resolveJsonModule": true,
"isolatedModules": true,
"jsx": "preserve",
"incremental": true,
"baseUrl": ".",
"paths": {
"@components/*": ["components/*"],
"@hooks/*": ["hooks/*"],
"@utils/*": ["utils/*"],
"@styles/*": ["styles/*"],
"@types/*": ["types/*"]
}
},
"include": ["next-env.d.ts", "**/*.ts", "**/*.tsx", "**/*.js"],
"exclude": ["node_modules"]
}
4. Sample Components Implementation
4.1. Button Component
A reusable Button component with Tailwind CSS and accessibility considerations.
// components/Button/Button.tsx
import React from 'react';
interface ButtonProps extends React.ButtonHTMLAttributes<HTMLButtonElement> {
label: string;
variant?: 'primary' | 'secondary';
}
const Button: React.FC<ButtonProps> = ({ label, variant = 'primary', ...props }) => {
const baseClasses =
'px-6 py-3 rounded-md font-semibold focus:outline-none focus:ring-2 focus:ring-offset-2';
const variantClasses =
variant === 'primary'
? 'bg-primary text-white hover:bg-secondary focus:ring-primary'
: 'bg-gray-200 text-gray-800 hover:bg-gray-300 focus:ring-gray-400';
return (
<button className={`${baseClasses} ${variantClasses}`} {...props}>
{label}
</button>
);
};
export default Button;
Explanation:
- Accessibility: The button includes focus styles for keyboard navigation.
- Variants: Supports
primary and secondary variants for flexibility.
- TypeScript: Props are strongly typed for reliability.
4.2. Header Component
A responsive Header with navigation links.
// components/Header/Header.tsx
import React from 'react';
import Link from 'next/link';
import { useTranslation } from 'next-i18next';
import Image from 'next/image';
import styles from './Header.module.css';
import Button from '../Button/Button';
const Header: React.FC = () => {
const { t } = useTranslation('common');
return (
<header className="fixed w-full bg-white shadow-md z-50">
<nav className="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8">
<div className="flex justify-between h-16">
{/* Logo */}
<div className="flex-shrink-0 flex items-center">
<Link href="/">
<a aria-label={t('logoAlt')}>
<Image src="/images/logo.png" alt={t('logoAlt')} width={40} height={40} />
</a>
</Link>
</div>
{/* Navigation Links */}
<div className="hidden md:flex space-x-8">
<Link href="#features">
<a className="text-gray-700 hover:text-primary">{t('features')}</a>
</Link>
<Link href="#testimonials">
<a className="text-gray-700 hover:text-primary">{t('testimonials')}</a>
</Link>
<Link href="#contact">
<a className="text-gray-700 hover:text-primary">{t('contact')}</a>
</Link>
</div>
{/* CTA Button */}
<div className="hidden md:flex items-center">
<Button label={t('getStarted')} onClick={() => { /* Handle Click */ }} />
</div>
</div>
</nav>
</header>
);
};
export default Header;
Explanation:
- Responsive Design: Navigation links are hidden on small screens (
md:hidden), can be enhanced with a mobile menu.
- Internationalization: Uses
next-i18next for translating text.
- Accessibility: Logo includes
aria-label for screen readers.
4.3. Hero Component with Animation
An animated Hero section using Framer Motion.
// components/Hero/Hero.tsx
import React from 'react';
import { motion } from 'framer-motion';
import Image from 'next/image';
import Button from '../Button/Button';
import styles from './Hero.module.css';
import { useTranslation } from 'next-i18next';
const Hero: React.FC = () => {
const { t } = useTranslation('common');
return (
<section
className="flex items-center justify-center h-screen bg-gray-100"
aria-labelledby="hero-heading"
>
<motion.div
initial={{ opacity: 0, y: -50 }}
animate={{ opacity: 1, y: 0 }}
transition={{ duration: 1 }}
className="text-center px-4"
>
<h1 id="hero-heading" className="text-4xl md:text-6xl font-bold text-gray-800">
{t('welcomeMessage')}
</h1>
<p className="mt-4 text-lg md:text-2xl text-gray-600">{t('heroSubtitle')}</p>
<div className="mt-8">
<Button label={t('getStarted')} onClick={() => { /* Handle Click */ }} />
</div>
</motion.div>
<Image
src="/images/hero-bg.jpg"
alt={t('heroAltText')}
layout="fill"
objectFit="cover"
className="absolute top-0 left-0 -z-10"
priority
/>
</section>
);
};
export default Hero;
Explanation:
- Animation: Uses Framer Motion to animate the Hero content's entrance.
- Image Optimization: Next.js
Image component optimizes the background image.
- Accessibility:
aria-labelledby links the section to the heading for screen readers.
- Internationalization: Text is translated using
next-i18next.
4.4. Footer Component
A simple Footer with social links.
// components/Footer/Footer.tsx
import React from 'react';
import Link from 'next/link';
import { useTranslation } from 'next-i18next';
const Footer: React.FC = () => {
const { t } = useTranslation('common');
return (
<footer className="bg-white py-6">
<div className="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8 text-center">
<p className="text-gray-600">© {new Date().getFullYear()} Your Company. {t('allRightsReserved')}</p>
<div className="mt-4">
<Link href="https://facebook.com" passHref>
<a className="text-gray-600 hover:text-primary mx-2" aria-label="Facebook">
{/* Replace with actual icons */}
<svg xmlns="http://www.w3.org/2000/svg" className="h-6 w-6" fill="currentColor" viewBox="0 0 24 24">
{/* SVG path */}
</svg>
</a>
</Link>
<Link href="https://twitter.com" passHref>
<a className="text-gray-600 hover:text-primary mx-2" aria-label="Twitter">
<svg xmlns="http://www.w3.org/2000/svg" className="h-6 w-6" fill="currentColor" viewBox="0 0 24 24">
{/* SVG path */}
</svg>
</a>
</Link>
{/* Add more social links as needed */}
</div>
</div>
</footer>
);
};
export default Footer;
Explanation:
- Accessibility: Social links include
aria-label for screen readers.
- Reusability: Easily extendable with more social platforms.
5. Pages Implementation
5.1. Custom App Component
Integrate global styles and internationalization.
// pages/_app.tsx
import type { AppProps } from 'next/app';
import '../styles/globals.css';
import Header from '../components/Header/Header';
import Footer from '../components/Footer/Footer';
import { appWithTranslation } from 'next-i18next';
import { useRouter } from 'next/router';
const MyApp = ({ Component, pageProps }: AppProps) => {
const router = useRouter();
return (
<>
<Header />
<main className="mt-16">
<Component {...pageProps} />
</main>
<Footer />
</>
);
};
export default appWithTranslation(MyApp);
Explanation:
- Layout: Includes
Header and Footer on every page.
- Internationalization: Wrapped with
appWithTranslation for next-i18next.
5.2. Home Page
Combine all components to form the landing page.
// pages/index.tsx
import type { NextPage } from 'next';
import Hero from '../components/Hero/Hero';
import Features from '../components/Features/Features';
import Testimonials from '../components/Testimonials/Testimonials';
import CTA from '../components/CTA/CTA';
import { serverSideTranslations } from 'next-i18next/serverSideTranslations';
const Home: NextPage = () => {
return (
<>
<Hero />
<Features />
<Testimonials />
<CTA />
</>
);
};
export const getStaticProps = async ({ locale }: { locale: string }) => ({
props: {
...(await serverSideTranslations(locale, ['common'])),
},
});
export default Home;
Explanation:
- Static Generation: Uses
getStaticProps for better performance.
- Internationalization: Loads translations for the current locale.
6. Internationalization (i18n) Setup
6.1. Configuration
Create next-i18next.config.js at the root:
// next-i18next.config.js
module.exports = {
i18n: {
defaultLocale: 'en',
locales: ['en', 'es'], // Add more locales as needed
},
};
Update next.config.js to include next-i18next:
// next.config.js
const { i18n } = require('./next-i18next.config');
module.exports = {
i18n,
images: {
domains: ['your-image-domain.com'], // Add your image domains if using external images
},
};
6.2. Translation Files
Create a public/locales directory with subdirectories for each language, e.g., en and es.
Example: public/locales/en/common.json
{
"logoAlt": "Company Logo",
"features": "Features",
"testimonials": "Testimonials",
"contact": "Contact",
"getStarted": "Get Started",
"welcomeMessage": "Welcome to Your Service",
"heroSubtitle": "We provide exceptional services to elevate your business.",
"heroAltText": "Hero Background Image",
"allRightsReserved": "All rights reserved."
}
Example: public/locales/es/common.json
{
"logoAlt": "Logotipo de la empresa",
"features": "Características",
"testimonials": "Testimonios",
"contact": "Contacto",
"getStarted": "Comenzar",
"welcomeMessage": "Bienvenido a Tu Servicio",
"heroSubtitle": "Ofrecemos servicios excepcionales para elevar tu negocio.",
"heroAltText": "Imagen de fondo del héroe",
"allRightsReserved": "Todos los derechos reservados."
}
7. State Management with Zustand
Implement a simple global state for theme toggling.
// hooks/useGlobalState.ts
import create from 'zustand';
interface GlobalState {
theme: 'light' | 'dark';
toggleTheme: () => void;
}
const useGlobalState = create<GlobalState>((set) => ({
theme: 'light',
toggleTheme: () =>
set((state) => ({
theme: state.theme === 'light' ? 'dark' : 'light',
})),
}));
export default useGlobalState;
Explanation:
- State: Manages a simple
theme state.
- Action: Provides a method to toggle the theme.
7.1. Theme Toggle in Header
Add a button in the Header to toggle themes.
// components/Header/Header.tsx
import React from 'react';
import Link from 'next/link';
import { useTranslation } from 'next-i18next';
import Image from 'next/image';
import Button from '../Button/Button';
import useGlobalState from '../../hooks/useGlobalState';
import { motion, AnimatePresence } from 'framer-motion';
const Header: React.FC = () => {
const { t } = useTranslation('common');
const { theme, toggleTheme } = useGlobalState();
return (
<header className="fixed w-full bg-white shadow-md z-50 dark:bg-gray-800">
<nav className="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8">
<div className="flex justify-between h-16">
{/* Logo */}
<div className="flex-shrink-0 flex items-center">
<Link href="/">
<a aria-label={t('logoAlt')}>
<Image src="/images/logo.png" alt={t('logoAlt')} width={40} height={40} />
</a>
</Link>
</div>
{/* Navigation Links */}
<div className="hidden md:flex space-x-8">
<Link href="#features">
<a className="text-gray-700 hover:text-primary dark:text-gray-200 dark:hover:text-primary">
{t('features')}
</a>
</Link>
<Link href="#testimonials">
<a className="text-gray-700 hover:text-primary dark:text-gray-200 dark:hover:text-primary">
{t('testimonials')}
</a>
</Link>
<Link href="#contact">
<a className="text-gray-700 hover:text-primary dark:text-gray-200 dark:hover:text-primary">
{t('contact')}
</a>
</Link>
</div>
{/* Right Side: Theme Toggle and CTA */}
<div className="hidden md:flex items-center space-x-4">
{/* Theme Toggle Button */}
<button
onClick={toggleTheme}
aria-label="Toggle Theme"
className="text-gray-700 hover:text-primary dark:text-gray-200 dark:hover:text-primary focus:outline-none"
>
<AnimatePresence exitBeforeEnter>
{theme === 'light' ? (
<motion.svg
key="sun"
xmlns="http://www.w3.org/2000/svg"
className="h-6 w-6"
fill="none"
viewBox="0 0 24 24"
stroke="currentColor"
initial={{ opacity: 0, rotate: -90 }}
animate={{ opacity: 1, rotate: 0 }}
exit={{ opacity: 0, rotate: 90 }}
transition={{ duration: 0.2 }}
>
<path
strokeLinecap="round"
strokeLinejoin="round"
strokeWidth={2}
d="M12 3v1m0 16v1m8.66-8.66h-1M4.34 12.34h-1m15.364-6.364l-.707.707M6.343 17.657l-.707.707m12.728 0l-.707-.707M6.343 6.343l-.707-.707M12 5a7 7 0 100 14 7 7 0 000-14z"
/>
</motion.svg>
) : (
<motion.svg
key="moon"
xmlns="http://www.w3.org/2000/svg"
className="h-6 w-6"
fill="none"
viewBox="0 0 24 24"
stroke="currentColor"
initial={{ opacity: 0, rotate: 90 }}
animate={{ opacity: 1, rotate: 0 }}
exit={{ opacity: 0, rotate: -90 }}
transition={{ duration: 0.2 }}
>
<path
strokeLinecap="round"
strokeLinejoin="round"
strokeWidth={2}
d="M21 12.79A9 9 0 1111.21 3 7 7 0 0021 12.79z"
/>
</motion.svg>
)}
</AnimatePresence>
</button>
{/* CTA Button */}
<Button label={t('getStarted')} onClick={() => { /* Handle Click */ }} />
</div>
</div>
</nav>
</header>
);
};
export default Header;
Explanation:
- Theme Management: Utilizes Zustand for managing theme state.
- Animation: Framer Motion animates the theme icons during toggling.
- Dark Mode Styling: Tailwind CSS
dark variant applies styles based on the theme.
7.2. Implementing Dark Mode with Tailwind CSS
Update globals.css to support dark mode:
/* styles/globals.css */
@tailwind base;
@tailwind components;
@tailwind utilities;
/* Enable dark mode */
@layer base {
body.dark {
@apply bg-gray-900 text-gray-100;
}
}
Modify _app.tsx to apply the theme class to the html element:
// pages/_app.tsx
import type { AppProps } from 'next/app';
import '../styles/globals.css';
import Header from '../components/Header/Header';
import Footer from '../components/Footer/Footer';
import { appWithTranslation } from 'next-i18next';
import { useEffect } from 'react';
import useGlobalState from '../hooks/useGlobalState';
const MyApp = ({ Component, pageProps }: AppProps) => {
const { theme } = useGlobalState();
useEffect(() => {
const root = window.document.documentElement;
if (theme === 'dark') {
root.classList.add('dark');
} else {
root.classList.remove('dark');
}
}, [theme]);
return (
<>
<Header />
<main className="mt-16">
<Component {...pageProps} />
</main>
<Footer />
</>
);
};
export default appWithTranslation(MyApp);
Explanation:
- Dark Mode: Applies or removes the
dark class based on the current theme, enabling Tailwind's dark mode styles.
8. Accessibility Enhancements
8.1. Semantic HTML
Ensure all components use semantic HTML elements where appropriate. For example, use <header>, <nav>, <main>, <section>, <footer>, etc., to improve accessibility and SEO.
8.2. ARIA Attributes
Add ARIA attributes to enhance screen reader support. For example, in navigation links, buttons, and modals, include appropriate aria-label, aria-expanded, etc.
8.3. Keyboard Navigation
Ensure all interactive elements are focusable and navigable via keyboard. Tailwind CSS's focus utilities help in styling focus states.
8.4. Color Contrast
Adhere to WCAG guidelines for color contrast. Tailwind CSS's utility classes assist in maintaining sufficient contrast ratios.
9. Testing Components
9.1. Example: Testing the Button Component
Create a test file Button.test.tsx in the components/Button/__tests__/ directory.
// components/Button/__tests__/Button.test.tsx
import React from 'react';
import { render, screen, fireEvent } from '@testing-library/react';
import Button from '../Button';
describe('Button Component', () => {
it('renders with the correct label', () => {
render(<Button label="Click Me" />);
const buttonElement = screen.getByRole('button', { name: /click me/i });
expect(buttonElement).toBeInTheDocument();
});
it('calls the onClick handler when clicked', () => {
const handleClick = jest.fn();
render(<Button label="Click Me" onClick={handleClick} />);
const buttonElement = screen.getByRole('button', { name: /click me/i });
fireEvent.click(buttonElement);
expect(handleClick).toHaveBeenCalledTimes(1);
});
it('applies the correct variant classes', () => {
const { rerender } = render(<Button label="Primary" variant="primary" />);
const primaryButton = screen.getByRole('button', { name: /primary/i });
expect(primaryButton).toHaveClass('bg-primary');
rerender(<Button label="Secondary" variant="secondary" />);
const secondaryButton = screen.getByRole('button', { name: /secondary/i });
expect(secondaryButton).toHaveClass('bg-gray-200');
});
});
Explanation:
- Test Cases:
- Verifies that the button renders with the correct label.
- Ensures that the
onClick handler is called upon clicking.
- Checks that the correct variant classes are applied based on props.
9.2. Running Tests
Add the following script to package.json to run tests:
"scripts": {
// ...other scripts
"test": "jest"
}
Run tests using:
npm run test
10. Storybook for UI Components
Set up Storybook to visualize and test UI components in isolation.
10.1. Example: Button Stories
Create a Storybook file Button.stories.tsx in the stories directory.
// stories/Button.stories.tsx
import React from 'react';
import { Meta, Story } from '@storybook/react';
import Button from '../components/Button/Button';
export default {
title: 'Components/Button',
component: Button,
} as Meta;
const Template: Story<React.ComponentProps<typeof Button>> = (args) => <Button {...args} />;
export const Primary = Template.bind({});
Primary.args = {
label: 'Primary Button',
variant: 'primary',
};
export const Secondary = Template.bind({});
Secondary.args = {
label: 'Secondary Button',
variant: 'secondary',
};
export const Disabled = Template.bind({});
Disabled.args = {
label: 'Disabled Button',
variant: 'primary',
disabled: true,
};
Explanation:
- Stories:
- Primary: Showcases the primary variant.
- Secondary: Showcases the secondary variant.
- Disabled: Shows the button in a disabled state.
10.2. Running Storybook
Add the following script to package.json:
"scripts": {
// ...other scripts
"storybook": "start-storybook -p 6006",
"build-storybook": "build-storybook"
}
Start Storybook using:
npm run storybook
11. Deployment
11.1. Deploying to Vercel
Vercel offers seamless integration with Next.js projects.
- Push to GitHub: Ensure your project is pushed to a Git repository on GitHub, GitLab, or Bitbucket.
- Import Project:
- Log in to Vercel.
- Click on "New Project" and import your repository.
- Configure Settings:
- Vercel automatically detects Next.js settings.
- Ensure environment variables (if any) are set.
- Deploy:
- Click "Deploy" and Vercel will build and deploy your project.
- Continuous Deployment:
- Subsequent pushes to the main branch will trigger automatic deployments.
11.2. Optimizing for Production
- Next.js Image Optimization: Ensure you're using the Next.js
Image component for all images.
- Analyze Bundle Size: Use Webpack Bundle Analyzer to monitor and reduce bundle sizes.
- Enable Incremental Static Regeneration (ISR): Allow Next.js to update static pages after deployment without rebuilding the entire site.
12. Conclusion
By following this guide, you've set up a robust and scalable landing page template using modern technologies and best practices. Here's a recap of the key points:
- Scalability: Modular component structure and state management with Zustand allow easy expansion.
- Maintainability: TypeScript ensures type safety, and tools like ESLint and Prettier maintain code quality.
- Accessibility: Semantic HTML, ARIA attributes, and keyboard navigation support make the site accessible.
- Inclusivity: Internationalization with
next-i18next caters to a global audience.
- Performance: Optimizations like Next.js Image component and code splitting enhance performance.
- Security: Best practices like input sanitization and dependency management secure the application.
Feel free to customize and extend this template to fit specific project requirements. Continuous learning and adherence to evolving best practices will further enhance your development workflow and project quality.
Happy Coding! 🚀