From 21258a5b617f70299b2e0ef539d797dd46080e78 Mon Sep 17 00:00:00 2001 From: Roman Hotsiy Date: Mon, 30 Sep 2019 09:54:19 +0300 Subject: [PATCH] fix: fix scrollYOffset when SSR --- .../StickySidebar/StickyResponsiveSidebar.tsx | 72 ++++++++++--------- 1 file changed, 39 insertions(+), 33 deletions(-) diff --git a/src/components/StickySidebar/StickyResponsiveSidebar.tsx b/src/components/StickySidebar/StickyResponsiveSidebar.tsx index 5a9f1817..5b4aa394 100644 --- a/src/components/StickySidebar/StickyResponsiveSidebar.tsx +++ b/src/components/StickySidebar/StickyResponsiveSidebar.tsx @@ -19,6 +19,10 @@ export interface StickySidebarProps { menu: MenuStore; } +export interface StickySidebarState { + offsetTop?: string; +} + const stickyfill = Stickyfill && Stickyfill(); const StyledStickySidebar = styled.div<{ open?: boolean }>` @@ -77,13 +81,26 @@ const FloatingButton = styled.div` `; @observer -export class StickyResponsiveSidebar extends React.Component { +export class StickyResponsiveSidebar extends React.Component< + StickySidebarProps, + StickySidebarState +> { + static contextType = OptionsContext; + context!: React.ContextType; + state: StickySidebarState = {}; + stickyElement: Element; componentDidMount() { if (stickyfill) { stickyfill.add(this.stickyElement); } + + // rerender when hydrating from SSR + // see https://github.com/facebook/react/issues/8017#issuecomment-256351955 + this.setState({ + offsetTop: this.getScrollYOffset(this.context), + }); } componentWillUnmount() { @@ -92,7 +109,7 @@ export class StickyResponsiveSidebar extends React.Component } } - getScrollYOffset(options) { + getScrollYOffset(options: RedocNormalizedOptions) { let top; if (this.props.scrollYOffset !== undefined) { top = RedocNormalizedOptions.normalizeScrollYOffset(this.props.scrollYOffset)(); @@ -105,43 +122,32 @@ export class StickyResponsiveSidebar extends React.Component render() { const open = this.props.menu.sideBarOpened; - const style = options => { - const top = this.getScrollYOffset(options); - return { - top, - height: `calc(100vh - ${top})`, - }; - }; + const top = this.state.offsetTop || this.getScrollYOffset(this.context); return ( - - {options => ( - <> - { - this.stickyElement = el as any; - }} - > - {this.props.children} - - - - - - )} - + <> + { + this.stickyElement = el as any; + }} + > + {this.props.children} + + + + + ); } private toggleNavMenu = () => { this.props.menu.toggleSidebar(); }; - - // private closeNavMenu = () => { - // this.setState({ open: false }); - // }; }