乐闻世界logo
搜索文章和话题

How to display a local video in NextJS?

1个答案

1

There are two primary methods for using local videos in Next.js: utilizing the HTML <video> tag or employing third-party libraries (such as react-player). Below, I will provide a detailed explanation of both methods.

Using the HTML <video> tag

In Next.js, you can directly embed local video files using the HTML5 <video> tag. Here are the basic steps:

Step 1: Place the video file in the public folder. In Next.js, content within the public folder is accessible as static resources.

Step 2: In your component, use the <video> tag and reference your video file via the src attribute.

Example code:

jsx
import React from 'react'; const VideoComponent = () => { return ( <div> <video width="750" height="500" controls> <source src="/videos/example.mp4" type="video/mp4" /> Your browser does not support the video tag. </video> </div> ); }; export default VideoComponent;

In this example, the video file example.mp4 should be placed in the public/videos/ directory. The controls attribute is optional and provides basic playback controls such as play and pause.

Using third-party libraries like react-player

react-player is a React component for embedding video players that supports various video sources, including local files. Using this library offers enhanced customization options and playback controls.

Step 1: Install the react-player library.

bash
npm install react-player # or yarn add react-player

Step 2: Import react-player in your component and use it to load the video.

Example code:

jsx
import React from 'react'; import ReactPlayer from 'react-player'; const VideoComponent = () => { return ( <div> <ReactPlayer url="/videos/example.mp4" width="100%" height="100%" controls /> </div> ); }; export default VideoComponent;

In this example, as before, the video file example.mp4 should be located in the public/videos/ directory. The ReactPlayer component accepts multiple optional props, such as controls for playback controls, width and height to set the player dimensions, and others.

Both methods are the most common approaches for using local videos in Next.js. Depending on project requirements and video usage scenarios, you can choose the most suitable method. Using the <video> tag is the simplest and most direct approach, but if you need more complex player features such as playlists or custom styling, using react-player may be a better choice.

2024年6月29日 12:07 回复

你的答案