fix(v2): Fix Collapsible hydration layout shift (#5159)

This commit is contained in:
Sébastien Lorber 2021-07-13 17:31:26 +02:00 committed by GitHub
parent fa9b0cd9c1
commit f33cd079c2
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23

View file

@ -5,6 +5,7 @@
* LICENSE file in the root directory of this source tree. * LICENSE file in the root directory of this source tree.
*/ */
import ExecutionEnvironment from '@docusaurus/ExecutionEnvironment';
import React, { import React, {
useState, useState,
useEffect, useEffect,
@ -146,9 +147,17 @@ function useCollapseAnimation({
} }
type CollapsibleElementType = React.ElementType< type CollapsibleElementType = React.ElementType<
Pick<React.HTMLAttributes<unknown>, 'className' | 'onTransitionEnd'> Pick<React.HTMLAttributes<unknown>, 'className' | 'onTransitionEnd' | 'style'>
>; >;
// Prevent hydration layout shift before anims are handled imperatively with JS
function getSSRStyle(collapsed: boolean) {
if (ExecutionEnvironment.canUseDOM) {
return undefined;
}
return collapsed ? CollapsedStyles : ExpandedStyles;
}
export function Collapsible({ export function Collapsible({
as: As = 'div', as: As = 'div',
collapsed, collapsed,
@ -171,6 +180,7 @@ export function Collapsible({
<As <As
// @ts-expect-error: see https://twitter.com/sebastienlorber/status/1412784677795110914 // @ts-expect-error: see https://twitter.com/sebastienlorber/status/1412784677795110914
ref={collapsibleRef} ref={collapsibleRef}
style={getSSRStyle(collapsed)}
onTransitionEnd={(e) => { onTransitionEnd={(e) => {
if (e.propertyName !== 'height') { if (e.propertyName !== 'height') {
return; return;