Certainly! Below is a comprehensive solution that includes a custom React hook named useTailwindBreakpoint. This hook takes a Tailwind CSS breakpoint ("sm", "md", "lg", etc.) and an optional strict boolean as inputs and returns a boolean indicating whether the current screen width matches the specified criteria.
Overview
-
Breakpoint Definitions: Define Tailwind CSS breakpoints in a TypeScript enum for type safety and easy reference.
-
Custom Hook (useTailwindBreakpoint):
- Parameters:
size: The breakpoint size ("sm", "md", "lg", etc.).
strict (optional): A boolean indicating whether to use strict mode.
- Return Value: A boolean indicating whether the current screen width matches the criteria.
- Functionality:
- Utilizes
window.matchMedia to listen for changes in screen width.
- In non-strict mode, returns
true if the screen width is equal to or greater than the specified breakpoint.
- In strict mode, returns
true only if the screen width is within the range of the specified breakpoint.
-
SSR Considerations: Ensures compatibility with Next.js's Server-Side Rendering (SSR) by checking if the window object is available.
-
Usage Example: Demonstrates how to use the useTailwindBreakpoint hook within a Next.js component.
Implementation
1. Define Tailwind Breakpoints
First, define the Tailwind CSS breakpoints in a TypeScript enum for clarity and type safety.
// tailwindBreakpoints.ts
export type TailwindBreakpoint = 'sm' | 'md' | 'lg' | 'xl' | '2xl';
export const tailwindBreakpoints: Record<TailwindBreakpoint, number> = {
sm: 640,
md: 768,
lg: 1024,
xl: 1280,
'2xl': 1536,
};
2. Create the Custom Hook
Now, create the useTailwindBreakpoint hook that utilizes the defined breakpoints.
// useTailwindBreakpoint.ts
import { useEffect, useState } from 'react';
import { tailwindBreakpoints, TailwindBreakpoint } from './tailwindBreakpoints';
type UseTailwindBreakpoint = (
size: TailwindBreakpoint,
strict?: boolean
) => boolean;
const useTailwindBreakpoint: UseTailwindBreakpoint = (size, strict = false) => {
const [isMatch, setIsMatch] = useState<boolean>(false);
useEffect(() => {
// Ensure window is defined (avoids SSR issues)
if (typeof window === 'undefined') {
return;
}
// Get the min-width for the current size
const minWidth = tailwindBreakpoints[size];
if (minWidth === undefined) {
console.error(`Invalid Tailwind breakpoint: ${size}`);
return;
}
let maxWidth: number | undefined = undefined;
if (strict) {
// Determine the next breakpoint to set the max-width
const breakpoints = Object.keys(tailwindBreakpoints) as TailwindBreakpoint[];
const currentIndex = breakpoints.indexOf(size);
if (currentIndex !== -1 && currentIndex < breakpoints.length - 1) {
const nextSize = breakpoints[currentIndex + 1];
maxWidth = tailwindBreakpoints[nextSize] - 1;
}
}
// Construct the media query
let query = `(min-width: ${minWidth}px)`;
if (strict && maxWidth !== undefined) {
query += ` and (max-width: ${maxWidth}px)`;
}
const mediaQueryList = window.matchMedia(query);
// Define a handler to update the state
const handleChange = (event: MediaQueryListEvent) => {
setIsMatch(event.matches);
};
// Set the initial state
setIsMatch(mediaQueryList.matches);
// Add the event listener
if (mediaQueryList.addEventListener) {
mediaQueryList.addEventListener('change', handleChange);
} else {
// For older browsers
mediaQueryList.addListener(handleChange);
}
// Cleanup listener on unmount
return () => {
if (mediaQueryList.removeEventListener) {
mediaQueryList.removeEventListener('change', handleChange);
} else {
mediaQueryList.removeListener(handleChange);
}
};
}, [size, strict]);
return isMatch;
};
export default useTailwindBreakpoint;
3. Usage Example
Here's how you can use the useTailwindBreakpoint hook within a Next.js component:
// ExampleComponent.tsx
import React from 'react';
import useTailwindBreakpoint from './useTailwindBreakpoint';
import { TailwindBreakpoint } from './tailwindBreakpoints';
interface ExampleComponentProps {
breakpoint: TailwindBreakpoint;
strict?: boolean;
}
const ExampleComponent: React.FC<ExampleComponentProps> = ({ breakpoint, strict = false }) => {
const isMatch = useTailwindBreakpoint(breakpoint, strict);
return (
<div>
<p>
The current screen is {strict ? 'exactly' : 'at least'} "{breakpoint}".
</p>
<p>Status: {isMatch ? 'Matched' : 'Not Matched'}</p>
</div>
);
};
export default ExampleComponent;
You can use this component anywhere in your Next.js application:
// pages/index.tsx
import React from 'react';
import ExampleComponent from '../components/ExampleComponent';
const HomePage: React.FC = () => {
return (
<div>
<h1>Tailwind Breakpoint Demo</h1>
<ExampleComponent breakpoint="md" strict={false} />
<ExampleComponent breakpoint="lg" strict={true} />
</div>
);
};
export default HomePage;
4. Handling Tailwind Configuration Changes
If you customize Tailwind's default breakpoints in your tailwind.config.js, ensure that the tailwindBreakpoints in tailwindBreakpoints.ts reflects those changes for consistency.
// tailwind.config.js
module.exports = {
theme: {
extend: {
screens: {
sm: '600px',
md: '800px',
// ... other custom breakpoints
},
},
},
};
Update the tailwindBreakpoints.ts accordingly:
// tailwindBreakpoints.ts
export type TailwindBreakpoint = 'sm' | 'md' | 'lg' | 'xl' | '2xl';
export const tailwindBreakpoints: Record<TailwindBreakpoint, number> = {
sm: 600, // Updated from 640px
md: 800, // Updated from 768px
lg: 1024,
xl: 1280,
'2xl': 1536,
};
Notes
-
SSR Compatibility: The hook checks if window is defined to prevent issues during server-side rendering in Next.js.
-
Browser Support: The hook uses both addEventListener and addListener for broader browser compatibility.
-
Error Handling: If an invalid breakpoint is passed, it logs an error to the console.
-
Type Safety: TypeScript ensures that only valid Tailwind breakpoints are used.
Conclusion
This solution provides a reusable and dynamic way to reactively determine if the current screen width matches a specified Tailwind CSS breakpoint, with an option for strict range checking. By leveraging window.matchMedia and React's hooks, it ensures real-time responsiveness to screen size changes, making it an effective tool for responsive design in Next.js applications.