You are an expert software engineer specialised in Next.js with TypeScript. I need you to build me a reusable solution for when I input a TailwindCSS screen size (e.g., “sm”, “md”, “lg”, etc.) it returns true or false. It returns true if the screen width is equal or greater than the corresponding TailwindCSS minimum width. There’s a second optional input variable which informs whether strict or not. If it is strict, it returns falls when the size gets outside the range. For example, under strict mode, if the input size is “sm” and the screen width is “md” or greater in size, it will return false. Under not strict mode, it will return screen size equal or greater than the minimum width regardless of overlap with larger size categories. Make sure that this is dynamic, listening to screen size changes and updating the output boolean output when necessary.
Assistant
Certainly! Below is a reusable solution implemented as a custom React hook using TypeScript for a Next.js application. This hook, useTailwindScreen, allows you to determine if the current screen size matches a specified TailwindCSS breakpoint, with an optional strict mode.
strict (optional): A boolean to determine strict mode. Defaults to false.
Output:
A boolean indicating whether the current screen size matches the criteria based on the inputs.
Behavior:
Non-Strict Mode (strict = false): Returns true if the screen width is equal to or greater than the specified breakpoint.
Strict Mode (strict = true): Returns true only if the screen width is within the range of the specified breakpoint and less than the next larger breakpoint.
Dynamic Listening:
The hook listens to window resize events and updates the boolean value accordingly.
Implementation
typescript
// hooks/useTailwindScreen.ts
import { useState, useEffect } from 'react';
/**
* TailwindCSS default breakpoints in pixels.
*/
const tailwindBreakpoints: Record<string, number> = {
sm: 640,
md: 768,
lg: 1024,
xl: 1280,
'2xl': 1536,
};
/**
* Sorted array of breakpoint names based on their min-width.
*/
const sortedBreakpoints = Object.keys(tailwindBreakpoints).sort(
(a, b) => tailwindBreakpoints[a] - tailwindBreakpoints[b]
) as Array<keyof typeof tailwindBreakpoints>;
/**
* Custom hook to determine if the current screen size matches a TailwindCSS breakpoint.
*
* @param size - The TailwindCSS breakpoint to check (e.g., 'sm', 'md', 'lg', etc.).
* @param strict - If true, the hook checks if the screen width is within the exact range of the breakpoint.
* If false, it checks if the screen width is equal to or greater than the breakpoint's min-width.
* Defaults to false.
* @returns A boolean indicating whether the current screen size matches the criteria.
*/
function useTailwindScreen(
size: keyof typeof tailwindBreakpoints,
strict: boolean = false
): boolean {
const [matches, setMatches] = useState<boolean>(false);
useEffect(() => {
if (typeof window === 'undefined') {
// If window is undefined (e.g., during SSR), return false
return;
}
const minWidth = tailwindBreakpoints[size];
let maxWidth: number | undefined;
if (strict) {
const currentIndex = sortedBreakpoints.indexOf(size);
if (currentIndex === -1) {
console.warn(`Invalid Tailwind breakpoint: ${size}`);
return;
}
if (currentIndex < sortedBreakpoints.length - 1) {
const nextSize = sortedBreakpoints[currentIndex + 1];
maxWidth = tailwindBreakpoints[nextSize] - 1;
}
}
let query = `(min-width: ${minWidth}px)`;
if (strict && maxWidth !== undefined) {
query += ` and (max-width: ${maxWidth}px)`;
}
const mediaQueryList = window.matchMedia(query);
const updateMatch = (e: MediaQueryListEvent | MediaQueryList) => {
setMatches(e.matches);
};
// Initial check
setMatches(mediaQueryList.matches);
// Add listener
if (mediaQueryList.addEventListener) {
mediaQueryList.addEventListener('change', updateMatch);
} else {
// For older browsers
mediaQueryList.addListener(updateMatch);
}
// Cleanup listener on unmount
return () => {
if (mediaQueryList.removeEventListener) {
mediaQueryList.removeEventListener('change', updateMatch);
} else {
mediaQueryList.removeListener(updateMatch);
}
};
}, [size, strict]);
return matches;
}
export default useTailwindScreen;
Usage Example
Here's how you can use the useTailwindScreen hook within a component:
typescript
// components/ResponsiveComponent.tsx
import React from 'react';
import useTailwindScreen from '../hooks/useTailwindScreen';
const ResponsiveComponent: React.FC = () => {
// Check if the screen is at least 'md' breakpoint
const isMediumOrLarger = useTailwindScreen('md');
// Check if the screen is exactly 'sm' breakpoint (strict mode)
const isSmallStrict = useTailwindScreen('sm', true);
return (
<div>
{isMediumOrLarger && <p>The screen is medium or larger.</p>}
{isSmallStrict && <p>The screen is exactly small.</p>}
{!isSmallStrict && <p>The screen is larger than small.</p>}
</div>
);
};
export default ResponsiveComponent;
Explanation
Breakpoint Mapping:
The tailwindBreakpoints object maps TailwindCSS breakpoint names to their corresponding minimum widths in pixels.
sortedBreakpoints is an array of breakpoint names sorted by their min-widths to easily determine the range for strict mode.
Hook Logic:
Non-Strict Mode:
Constructs a media query that checks if the screen width is at least the specified breakpoint's min-width.
Strict Mode:
Constructs a media query that checks if the screen width is between the specified breakpoint's min-width and just below the next breakpoint's min-width.
For example, for size = 'sm' and strict = true, it checks for min-width: 640px and max-width: 767px.
Media Query Listener:
Uses window.matchMedia to create a media query list based on the constructed query.
Adds an event listener to update the matches state whenever the screen size changes and the media query state changes.
Handles both modern (addEventListener) and older (addListener) browser APIs for media queries.
Cleans up the event listener when the component unmounts or when dependencies change.
SSR Handling:
Since Next.js performs server-side rendering, the hook first checks if window is defined to prevent errors during SSR. If window is undefined, it defaults to false.
Customization
Custom Breakpoints:
If you're using custom breakpoints in your TailwindCSS configuration, you can modify the tailwindBreakpoints object accordingly.
Type Extensions:
For enhanced type safety, you can define a TypeScript type for the breakpoint sizes based on your Tailwind configuration.
Conclusion
This useTailwindScreen hook provides a flexible and reusable way to interact with TailwindCSS breakpoints dynamically within your Next.js applications. It ensures responsiveness by listening to screen size changes and updating component states accordingly.