3

React 18 adds onResize event to video elements

 2 years ago
source link: https://blog.saeloun.com/2022/05/19/react-18-adds-onresize-event-to-video
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
neoserver,ios ssh client

React 18 adds onResize event to video elements

May 19, 2022 , by Jijo Bose

1 minute read

SyntheticEvent in React is a cross-browser wrapper similar to browers’s native events; It has the same interface as the browser’s native event, including stopPropagation() and preventDefault(), except the events work identically across all browsers.

Until React 18, React’s synthetic media events contain several existing media events, for instance onLoadedMetadata and onVolumeChange. But there is no onResize handler.

Before

<video> element with a onResize prop would display a warning

Warning: Unknown event handler property `onResize`. It will be ignored.

After

With the changes in React 18, onResize props are added to <video> element that triggers when one or both of the videoWidth and videoHeight attributes have just been updated.

It’s useful for responding to resolution changes in video players.

Sample Code

import { useState } from "react";
import "./styles.css";

const VIDEO_LINKS = [
  "https://www.sample-videos.com/video123/mp4/240/big_buck_bunny_240p_2mb.mp4",
  "https://www.sample-videos.com/video123/mp4/480/big_buck_bunny_480p_2mb.mp4",
  "https://www.sample-videos.com/video123/mp4/720/big_buck_bunny_720p_20mb.mp4"
];

export default function App() {
  const [switchVideo, setSwitchVideo] = useState(0);
  const [videoWidth, setVideoWidth] = useState(null);
  const [videoHeight, setVideoHeight] = useState(null);

  return (
    <div className="App">
      <video
        src={VIDEO_LINKS[switchVideo]}
        controls
        style=
        onResize={(e) => {
          setVideoWidth(e.target.videoWidth);
          setVideoHeight(e.target.videoHeight);
        }}
      />
      <div className="resButton">
        <button onClick={() => setSwitchVideo(0)}>240p</button>
        <button onClick={() => setSwitchVideo(1)}>480p</button>
        <button onClick={() => setSwitchVideo(2)}>720p</button>
      </div>
    </div>
  );
}
onresize_sample.gif

About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK