Skip to content

Commit

Permalink
fix(gatsby-image): Don't assume DOM state is valid at hydration stage (
Browse files Browse the repository at this point in the history
  • Loading branch information
polarathene committed Sep 15, 2020
1 parent 8636370 commit cf34304
Showing 1 changed file with 18 additions and 6 deletions.
24 changes: 18 additions & 6 deletions packages/gatsby-image/src/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -358,6 +358,7 @@ class Image extends React.Component {
imgLoaded: false,
imgCached: false,
fadeIn: !this.seenBefore && props.fadeIn,
isHydrated: false,
}

this.imageRef = React.createRef()
Expand All @@ -367,6 +368,10 @@ class Image extends React.Component {
}

componentDidMount() {
this.setState({
isHydrated: isBrowser,
})

if (this.state.isVisible && typeof this.props.onStartLoad === `function`) {
this.props.onStartLoad({ wasCached: inImageCache(this.props) })
}
Expand Down Expand Up @@ -445,6 +450,12 @@ class Image extends React.Component {
draggable,
} = convertProps(this.props)

const imageVariants = fluid || fixed
// Abort early if missing image data (#25371)
if (!imageVariants) {
return null
}

const shouldReveal = this.state.fadeIn === false || this.state.imgLoaded
const shouldFadeIn = this.state.fadeIn === true && !this.state.imgCached

Expand Down Expand Up @@ -476,10 +487,14 @@ class Image extends React.Component {
itemProp,
}

if (fluid) {
const imageVariants = fluid
const image = getCurrentSrcData(fluid)
// Initial client render state needs to match SSR until hydration finishes.
// Once hydration completes, render again to update to the correct image.
// `imageVariants` is always an Array type at this point due to `convertProps()`
const image = !this.state.isHydrated
? imageVariants[0]
: getCurrentSrcData(imageVariants)

if (fluid) {
return (
<Tag
className={`${className ? className : ``} gatsby-image-wrapper`}
Expand Down Expand Up @@ -585,9 +600,6 @@ class Image extends React.Component {
}

if (fixed) {
const imageVariants = fixed
const image = getCurrentSrcData(fixed)

const divStyle = {
position: `relative`,
overflow: `hidden`,
Expand Down

0 comments on commit cf34304

Please sign in to comment.