#root
View Compiled
const {useRef, forwardRef, useImperativeHandle} = React;
const {render} = ReactDOM;

// Renvoi le la référence avec `forwardRef`
const CustomAudio = forwardRef(function (props, ref) {
  // Récupération de la référence de l'audio
  const audioRef = useRef();
  const forward = () => {
    audioRef.current.currentTime += 10;
  };
  // Personnalisation de la référence renvoyée
  useImperativeHandle(ref, () => ({
    // La fonction play de l'audio est renvoyée
    play: () => audioRef.current.play(),
    // Notre fonction renvoyée via la propriété `forward`
    forward: forward,
  }));

  return (
    <audio
      ref={audioRef}
      src="https://www.bensound.com/bensound-music/bensound-happyrock.mp3"
    />
  );
});

function Player() {
  const customAudioRef = useRef();
  const play = () => {
    customAudioRef.current.play()
  }
  
  const forward = () => {
    customAudioRef.current.forward();
  }
  
  return (
    <>
      <CustomAudio ref={customAudioRef} />
      <button onClick={play}> Play </button>
      <button onClick={forward}> +10 sec </button>
    </>
  )
}
      
render(<Player />, document.getElementById('root'))
View Compiled
Run Pen

External CSS

This Pen doesn't use any external CSS resources.

External JavaScript

  1. https://cdnjs.cloudflare.com/ajax/libs/babel-polyfill/7.8.7/polyfill.min.js
  2. https://cdnjs.cloudflare.com/ajax/libs/react/16.13.1/umd/react.production.min.js
  3. https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.13.1/umd/react-dom.production.min.js