mirror of
https://github.com/stackblitz-labs/bolt.diy
synced 2025-06-26 18:26:38 +00:00
Merge pull request #37 from vgcman16/codex/update-useviewport-for-ssr-compatibility
Fix SSR compatibility in useViewport
This commit is contained in:
commit
a87477f504
@ -1,10 +1,28 @@
|
|||||||
import { useState, useEffect } from 'react';
|
import { useState, useEffect } from 'react';
|
||||||
|
|
||||||
const useViewport = (threshold = 1024) => {
|
/**
|
||||||
const [isSmallViewport, setIsSmallViewport] = useState(window.innerWidth < threshold);
|
* Determine the current viewport width in both browser and server contexts.
|
||||||
|
* When `window` is not available (e.g. during SSR), a fallback width is used.
|
||||||
|
*/
|
||||||
|
const getWidth = (fallback: number): number =>
|
||||||
|
typeof window !== 'undefined' ? window.innerWidth : fallback;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Returns `true` if the viewport width is less than the provided threshold.
|
||||||
|
* A `fallbackWidth` can be supplied for server environments where `window`
|
||||||
|
* is undefined.
|
||||||
|
*/
|
||||||
|
const useViewport = (threshold = 1024, fallbackWidth = 1024) => {
|
||||||
|
const [isSmallViewport, setIsSmallViewport] = useState(
|
||||||
|
getWidth(fallbackWidth) < threshold,
|
||||||
|
);
|
||||||
|
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
const handleResize = () => setIsSmallViewport(window.innerWidth < threshold);
|
if (typeof window === 'undefined') return;
|
||||||
|
|
||||||
|
const handleResize = () =>
|
||||||
|
setIsSmallViewport(window.innerWidth < threshold);
|
||||||
|
|
||||||
window.addEventListener('resize', handleResize);
|
window.addEventListener('resize', handleResize);
|
||||||
|
|
||||||
return () => {
|
return () => {
|
||||||
|
Loading…
Reference in New Issue
Block a user