How can I add onClick event for Ref Element using React Hooks?

13.6k Views Asked by At

I want to toggle FullScreen. component has a toggleFullscreen method, but in docs just Class Components.

import React, { useRef } from 'react';

// Components
import { Player } from 'video-react';

export default () => {
const videoRef = useRef(null);

return (
  <div>
   <Player ref={videoRef} 
   src="https://media.w3.org/2010/05/sintel/trailer_hd.mp4" />
  </div>
 );
};
2

There are 2 best solutions below

0
Auskennfuchs On

If you want to toggle to fullscreen immediately after the component was mounted you can use useEffect to call the function

export default () => {
...
  React.useEffect(() => {
    videoRef.current.toggleFullscreen()

    // toggle back to normal mode when the component unmounts (optional)
    return () => {
     videoRef.current.toggleFullscreen()
    }
  }, [])

  return (
    ...
  )
}

The important part is the [] as second parameter. With this the toggle is only called once when mounting the component and not on every rerender.

0
AudioBubble On
import React, { useRef } from 'react';

// Components
import { Player, BigPlayButton } from 'video-react';

export default () => {
    const videoRef = useRef(null);
    const toggleFullScrn = () => videoRef.current.actions.toggleFullscreen();

    return (
        <div onClick={toggleFullScrn}>
            <Player ref={videoRef} src="https://media.w3.org/2010/05/sintel/trailer_hd.mp4">
                <BigPlayButton />
            </Player>
        </div>
    );
};