How to Create a picture-in-picture View in React

PIP (picture-in-picture) view is a “floating” window above all content in an app, that can be dragged, expanded and minimized.

PIP view can be useful in many cases, for example when we want to allow users to watch videos in a floating window (always on top of other content) so they can keep an eye on what they’re watching while interacting with other parts of the app.

Final Code

I fact, I created an npm package named ‘resizable-pip’, that does exactly what you will learn in this tutorial, so if you’re only interested in using it, you can install the package as follows:

How do we create a resizable PIP?

In this tutorial we will use 2 npm packages:

  1. react-draggable
  2. react-resizable

Initialization

Start by creating a new react project in an empty directory:

Then install the required dependencies:

Creating the components

Create a new file in /src/components/ named ‘PIP.jsx’

For styling, create a new file in /src/components/ named ‘PIP.module.css’

Here we are using the react-draggable package to create the most basic floating window, it can be dragged anywhere on top of our app’s content, but it still cannot be resized.

For that we will need to use the react-resizable package.

Create a new file in /src/components/ named ‘ResizablePIP.jsx’

And don’t forget styles as well, create a new file in /src/components/ named ‘PIP.module.css’

Here we are using the PIP component from earlier, and extending it with the ability to be resized, by using the react-resizable package.

Note the props this component can receive:

  1. children - the content that will be displayed inside our Resizable PIP window.
  2. width - the initial width of the PIP window.
  3. height - the initial height of the PIP window.
  4. minConstraints - the minimum size possible for the PIP window (width, height).
  5. maxConstraints - the maximum size possible for the PIP window (width, height).

All of these props are optional, so we specify default values.

Usage

To make an element in our app displayed in a floating resizable window, we can import our newly created ResizablePIP component, and use it as a wrapper for that element.

See how easy it is to make whatever element we want appear inside a floating resizable window. Just wrap it with a ResizablePIP component and you’re good to go.

Hope you find this tutorial useful, now go create some wonderful PIPs!

a person holding a photo of grand canal photo
Photo by Jakob Owens on Unsplash

Mobile & Web Developer. Founder & Developer at Sociallix.