Differing state after componentWillMount on client and server breaks SSR
disintegrator opened this issue · comments
Firstly, thanks for this library!
I'm currently trying to use react-media in a project which has SSR and seeing errors when the react tree mounts on the client-side (Warning: Did not expect server HTML to contain a <div> in <div>.
). Doing some experimentation on the side, I confirmed that the state of the Media component after componentWillMount
differs between client and server. if (typeof window !== "object") return
will cause it to skip calling updateMatches
on the server.
As I see it, the solution is to move the logic from componentWillMount
to componentDidMount
. If you agree, then I'd be happy to submit a PR with the change.
The typeof window
check is in componentWillMount
specifically to support SSR. The rest of the code in componentWillMount
When you're rendering server-side, you need to use the defaultMatches
prop to populate your initial state to whatever you think it will be on the client. For example, if you have a media query that is designed to target small screens, and the request is coming from a mobile device, you could do:
<Media query="(max-width: 500px)" defaultMatches={true} ... />
Hope that helps!