Skip to content

Commit 37c4d21

Browse files
authored
fix useViewportSize for ssr environment (#5163)
1 parent 3c10789 commit 37c4d21

File tree

2 files changed

+31
-1
lines changed

2 files changed

+31
-1
lines changed

packages/@react-aria/utils/src/useViewportSize.ts

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -11,6 +11,7 @@
1111
*/
1212

1313
import {useEffect, useState} from 'react';
14+
import {useIsSSR} from '@react-aria/ssr';
1415

1516
interface ViewportSize {
1617
width: number,
@@ -21,7 +22,8 @@ interface ViewportSize {
2122
let visualViewport = typeof document !== 'undefined' && window.visualViewport;
2223

2324
export function useViewportSize(): ViewportSize {
24-
let [size, setSize] = useState(() => getViewportSize());
25+
let isSSR = useIsSSR();
26+
let [size, setSize] = useState(() => isSSR ? {width: 0, height: 0} : getViewportSize());
2527

2628
useEffect(() => {
2729
// Use visualViewport api to track available height even on iOS virtual keyboard opening
Lines changed: 28 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,28 @@
1+
/*
2+
* Copyright 2020 Adobe. All rights reserved.
3+
* This file is licensed to you under the Apache License, Version 2.0 (the "License");
4+
* you may not use this file except in compliance with the License. You may obtain a copy
5+
* of the License at http://www.apache.org/licenses/LICENSE-2.0
6+
*
7+
* Unless required by applicable law or agreed to in writing, software distributed under
8+
* the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR REPRESENTATIONS
9+
* OF ANY KIND, either express or implied. See the License for the specific language
10+
* governing permissions and limitations under the License.
11+
*/
12+
13+
import {testSSR} from '@react-spectrum/test-utils';
14+
15+
describe('useViewportSize SSR', () => {
16+
it('should render without errors', async () => {
17+
await testSSR(__filename, `
18+
import {useViewportSize} from '../src';
19+
20+
function Viewport() {
21+
useViewportSize();
22+
return null;
23+
}
24+
25+
<Viewport />
26+
`);
27+
});
28+
});

0 commit comments

Comments
 (0)