Skip to content

Commit cf34304

Browse files
authoredSep 15, 2020
fix(gatsby-image): Don't assume DOM state is valid at hydration stage (#26097)
1 parent 8636370 commit cf34304

File tree

1 file changed

+18
-6
lines changed

1 file changed

+18
-6
lines changed
 

‎packages/gatsby-image/src/index.js

+18-6
Original file line numberDiff line numberDiff line change
@@ -358,6 +358,7 @@ class Image extends React.Component {
358358
imgLoaded: false,
359359
imgCached: false,
360360
fadeIn: !this.seenBefore && props.fadeIn,
361+
isHydrated: false,
361362
}
362363

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

369370
componentDidMount() {
371+
this.setState({
372+
isHydrated: isBrowser,
373+
})
374+
370375
if (this.state.isVisible && typeof this.props.onStartLoad === `function`) {
371376
this.props.onStartLoad({ wasCached: inImageCache(this.props) })
372377
}
@@ -445,6 +450,12 @@ class Image extends React.Component {
445450
draggable,
446451
} = convertProps(this.props)
447452

453+
const imageVariants = fluid || fixed
454+
// Abort early if missing image data (#25371)
455+
if (!imageVariants) {
456+
return null
457+
}
458+
448459
const shouldReveal = this.state.fadeIn === false || this.state.imgLoaded
449460
const shouldFadeIn = this.state.fadeIn === true && !this.state.imgCached
450461

@@ -476,10 +487,14 @@ class Image extends React.Component {
476487
itemProp,
477488
}
478489

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

497+
if (fluid) {
483498
return (
484499
<Tag
485500
className={`${className ? className : ``} gatsby-image-wrapper`}
@@ -585,9 +600,6 @@ class Image extends React.Component {
585600
}
586601

587602
if (fixed) {
588-
const imageVariants = fixed
589-
const image = getCurrentSrcData(fixed)
590-
591603
const divStyle = {
592604
position: `relative`,
593605
overflow: `hidden`,

0 commit comments

Comments
 (0)
Please sign in to comment.