twobin/react-lazyload

SSR : Did not expect server HTML to contain a <div> in <div>

Closed this issue · 2 comments

Hi There --

When using this library in a SSR environment, any code wrapped in <LazyLoad> doesn't get rendered by the server thereby eliminating it's SEO value. To counter this, I created a lazyload-wrapper component that looks like the following based on some of the conversation in this library.

import React from 'react';
import LazyLoad from 'react-lazyload';

const LazyloadWrapper = (props) => {

  if (typeof window === 'undefined') {
    return <div>{props.children}</div>;
  }
  return <LazyLoad>{props.children}</LazyLoad>;
}

export default LazyloadWrapper;

This spits out the following warning though on every page reload:

index.js:1 Warning: Did not expect server HTML to contain a <div> in <div>.
    in div (created by LazyLoad)
    in LazyLoad (at lazyload-wrapper.jsx:9)
    in div (at lazyload-wrapper.jsx:9)
    in LazyloadWrapper (at mkt/index.jsx:44)
    in div (created by Container)
    in Container (at mkt/index.jsx:43)
    in div (at mkt/index.jsx:42)

That warning is the end of the world but is there anyway to get the server & client side code to match without sacrificing the SEO-benefits of that content?

  1. You can use an SSR framework, such as Next.js, to render LazyLoad components only on the client side, which provides the ability to handle components differently on the server side and on the client side.

Disable LazyLoad components in server-side rendering
Disable LazyLoad components during server-side rendering, and enable LazyLoad only on the client side.

`const LazyloadWrapper = (props) => {
const [isClient, setIsClient] = React.useState(false);

React.useEffect(() => {
setIsClient(true);
}, []);

if (!isClient) {
Remove LazyLoad component from return null; // server-side rendering
}

return {props.children};
}`

Can you apply this code

@kyoungholee -- thanks for the reply though it's been awhile.

I'm pretty sure both versions of our code accomplish the same thing. Either way, I've found ways to navigate this issue via next/dynamic and conditional imports (like the above) if, for instance, some libraries are only available client-side.

I'll close this issue.