javascriptnode.jsreactjsreact-player

ReactPlayer doesn't load videos initially


I am using ReactPlayer in my React application to display videos, which are stored in a local folder. However, I'm facing an issue where the videos don't load initially when the page is loaded or refreshed. I have included the relevant code snippet below:

return (
  <div>
    <ReactPlayer key={1} url={"videos/1.mp4"} controls={true} />
  </div>
)

Upon loading or refreshing the page, the player does not display anything initially, as shown in the following image:
enter image description here

However, I noticed that the video loads successfully if I navigate to another page using the navbar and then switch back to the original page. This can be seen in the screenshots below:
enter image description here enter image description here

I have already checked GitHub issue #1520 related to this problem and attempted to upgrade my package based on the suggestions mentioned there. However, the issue still persists on my website.

Here are the versions of the packages I'm currently using:
"react": "^18.2.0"
"react-dom": "^18.2.0"
"react-player": "^2.12.0"
"react-router-dom": "^6.11.2"
"react-scripts": "^2.1.3"
Node.js:18.16.0

Additionally, I am running my application on the following browsers: Safari, Chrome, and Edge.


Solution

  • The issue with the code I provided is that the URL prop of the ReactPlayer component is set to a relative path (videos/1.mp4). To load videos successfully, I need to provide the full URL or a valid absolute path.

    The videos are stored in the public folder of my React application, so I can modify the code as follows:

    <ReactPlayer
      key={1}
      url={`${process.env.PUBLIC_URL}/videos/1.mp4`}
      controls={true}
    />
    

    By using process.env.PUBLIC_URL, I can ensure that the correct absolute path is constructed, taking into account the public URL of my React application. However, I still don't know why the videos could be loaded when switching from another page in the old code, but they work in the new code.