How to Import a Local Video as Source for the Video Tag in GatsbyJS

There are many ways to handle media in GatsbyJS, from simple to advanced. This is the simplest way I’ve found to import a local video file (here an mp4) and use it as a source for the video (<video>) tag in GatsbyJS (React).

If you don’t already have a folder for static assets, create one and add your video file in it. My folder is called videos and the video file is called my-video.mp4.

Go inside the React file where you want to import your video, add this line import MyVideo from "../content/videos/my-video.mp4" anywhere, as long as it’s below your import React from 'react' import.

Keep in mind that you might have to change the path ../content/videos/ depending on where your video folder is located relative to the file you want to import it into.

Now you’re storing a reference to your video file as MyVideo (a variable).

Now inside the same React file, you need to add the MyVideo variable inside your video element as the source attribute value, like this:

<video width="100%" height="100%"  preload='auto'>
 <source src={MyVideo} type="video/mp4" />
 Your browser does not support HTML5 video.
</video>

The code above must to be inside inside the React render() method to work.

Here’s all the working code extracted into a reusable React video component:

import React from "react";
import MyVideo from "../../content/videos/my-video.mp4";

class MyVideoComponent extends React.Component {
  render() {
    return (
      <video width="100%" height="100%" preload="auto">
        <source src={MyVideo} type="video/mp4" />
        Your browser does not support HTML5 video.
      </video>
    );
  }
}

export default MyVideoComponent

Now to import this video anywhere you like, you just need to import MyVideoComponent like this:

import MyVideoComponent from "../components/MyVideoComponent"

And place it inside your React file:

<MyVideoComponent/>

Again, you have to add your video component inside a render() method.

Is this the best way to work with video in GatsbyJS?

No, it’s just the fastest way I know. There are many ways to handle video and other media in GatsbyJS. Among other things, you can use various compression, transformation and loading methods, which can massively boost performance on your site when implemented properly. I’ll save that for a future, and a bit more advanced tutorial (I’m still learning about it myself).


Has this been helpful to you?

You can support my work by sharing this article with others, or perhaps buy me a cup of coffee 😊

Kofi

Share & Discuss on