Skip to content

SSR: trust guessedBreakpoint during hydratation #38

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
wants to merge 1 commit into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
32 changes: 32 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -151,6 +151,38 @@ const markup = renderToString(
)
```

In order to avoid mismatch errors (`Warning: Did not expect server HTML to contain ...`), when the guessed breakpoint
is wrong, you need to provide the same `guessedBreakpoint` on both the server and the client.
Thanks to this, there will be no error during hydratation and ReactBreakpoint with still render the right
breakpoint once the app is mounted.
```js
// client.js

import ReactBreakpoints from 'react-breakpoints'

const breakpoints = {
mobile: 320,
mobileLandscape: 480,
tablet: 768,
tabletLandscape: 1024,
desktop: 1200,
desktopLarge: 1500,
desktopWide: 1920,
}

const guessedBreakpoint = window.guessedBreakpoint // you need to inject it from the server

ReactDOM.hydrate(
<ReactBreakpoints
guessedBreakpoint={guessedBreakpoint}
breakpoints={breakpoints}
>
<App />
</ReactBreakpoints>,
document.getElementById('root')
)
```

## Options

### `breakpointUnit: string` option
Expand Down
13 changes: 8 additions & 5 deletions modules/ReactBreakpoints.js
Original file line number Diff line number Diff line change
Expand Up @@ -68,15 +68,18 @@ class ReactBreakpoints extends React.Component {
let currentBreakpoint = null
const sortedBreakpoints = ReactBreakpoints.sortBreakpoints(breakpoints)

// if we are on the client, we directly compote the breakpoint using window width
if (global.window) {
// if there is a guessed breakpoint, we trust it on server AND on client (during hydrate),
// to avoid mismatch issues.
if (guessedBreakpoint) {
currentBreakpoint = ReactBreakpoints.calculateBreakpoint(
this.convertScreenWidth(global.window.innerWidth),
guessedBreakpoint,
sortedBreakpoints,
)
} else if (guessedBreakpoint) {
}
// if we are on the client, we directly compute the breakpoint using window width
else if (global.window) {
currentBreakpoint = ReactBreakpoints.calculateBreakpoint(
guessedBreakpoint,
this.convertScreenWidth(global.window.innerWidth),
sortedBreakpoints,
)
} else if (defaultBreakpoint) {
Expand Down