Trying to use react-player throws a Hydration error
Asked Answered
T

2

18

Hi how are you? I'm trying to use react-player in my Next.js app without any luck.

This code

import ReactPlayer from "react-player";

const Home = () => {
return (
  <div>
    <p>Here is my video!!</p>
    <div className={s.wrapper}>
      <ReactPlayer src='https://www.youtube.com/watch?v=zohpogt56Bg' width="100%" 
       height="100%" className={s.player} />
    </div>
  </div>
)}

keeps throwing this error: Error: Hydration failed because the initial UI does not match what was rendered on the server.

Does anybody knows what is going on? thanks!

Transformation answered 13/5, 2022 at 20:40 Comment(2)
Your function doesn't have a return?Chuipek
I'm having the same problem (using the url prop). versions are as follows: "next": "12.1.6", "react": "18.1.0", "react-dom": "18.1.0", "react-player": "^2.10.1"Brunn
B
45

You can change your import to utilize Next's dynamic import. If you are only using static site generation then this option should work for you. It does seem like a bandaid fix however, because I don't think it solves the root problem.

import dynamic from 'next/dynamic'
const ReactPlayer = dynamic(() => import("react-player"), { ssr: false });
Brunn answered 17/5, 2022 at 18:44 Comment(1)
How do I get typescript information?Rhomboid
B
21

Have you tried this?

It's basically checking the window.

import ReactPlayer from "react-player";

const Home = () => {
const [hasWindow, setHasWindow] = useState(false);
  useEffect(() => {
    if (typeof window !== "undefined") {
      setHasWindow(true);
    }
  }, []);
return (
  <div>
    <p>Here is my video!!</p>
    <div className={s.wrapper}>
      {
        hasWindow && <ReactPlayer src='https://www.youtube.com/watch?v=zohpogt56Bg' 
        width="100%" 
        height="100%" className={s.player} />
    }
    </div>
  </div>
)}
Barely answered 21/7, 2022 at 6:14 Comment(0)

© 2022 - 2025 — McMap. All rights reserved.