using the function useWindowDimensions in snacks web view returns an error:
“(0, _reactNative.useWindowDimensions) is not a function. (In ‘(0, _reactNative.useWindowDimensions)()’, ‘(0, _reactNative.useWindowDimensions)’ is undefined)”
Hi there! The useWindowDimensions hook doesn’t work on web yet. Unfortunately this is not well documented. Here are a few alternatives:
import { useEffect, useState } from 'react';
import { Dimensions, ScaledSize } from 'react-native';
type EventValue = {
window: ScaledSize;
screen: ScaledSize;
};
/**
* Listens to dimension changes of "dim".
*
* When a dimension changes, schedule this instantly. The other option is to
* schedules the update inside an animation frame (useDimensions) or to wait
* for an idle frame / until animations are done (useDimensionsIdle).
*
* @param dim screen or window, defaults to window
* @returns the ScaledSize of the dim
*/
export function useDimensionsSync(
dim: 'screen' | 'window' = 'window'
): ScaledSize {
const [dimensions, setDimensions] = useState(() => Dimensions.get(dim));
// Start listening to changes
useEffect(() => {
let stillCareAboutTheCallback = true;
const updateDimensions = (nextDimensions: EventValue) => {
stillCareAboutTheCallback && setDimensions(nextDimensions[dim]);
};
Dimensions.addEventListener('change', updateDimensions);
return () => {
stillCareAboutTheCallback = false;
Dimensions.removeEventListener('change', updateDimensions);
};
}, [dim, setDimensions]);
return dimensions;
}
export function useWindowDimensions() {
return useDimensionsSync('window')
}
Or if you need the JavaScript variant:
import { useEffect, useState } from 'react';
import { Dimensions } from 'react-native';
/**
* Listens to dimension changes of "dim".
*
* When a dimension changes, schedule this instantly. The other option is to
* schedules the update inside an animation frame (useDimensions) or to wait
* for an idle frame / until animations are done (useDimensionsIdle).
*
* @param dim screen or window, defaults to window
* @returns the ScaledSize of the dim
*/
export function useDimensionsSync(dim = 'window') {
const [dimensions, setDimensions] = useState(() => Dimensions.get(dim));
// Start listening to changes
useEffect(() => {
let stillCareAboutTheCallback = true;
const updateDimensions = (nextDimensions: EventValue) => {
stillCareAboutTheCallback && setDimensions(nextDimensions[dim]);
};
Dimensions.addEventListener('change', updateDimensions);
return () => {
stillCareAboutTheCallback = false;
Dimensions.removeEventListener('change', updateDimensions);
};
}, [dim, setDimensions]);
return dimensions;
}
export function useWindowDimensions() {
return useDimensionsSync('window')
}