dascritch / cpu-audio

An audio WebComponent to provide timecoded links and other features to an audio tag
https://dascritch.github.io/cpu-audio/
GNU Lesser General Public License v3.0
24 stars 2 forks source link

Example of React integration #120

Closed dascritch closed 3 years ago

dascritch commented 3 years ago

May be React developers may be interested in this component. We need to show an example and document caveats.

dascritch commented 3 years ago

Part needed here https://fr.reactjs.org/docs/web-components.html

The cpu-audio.js must be included in public/ and loaded from the HTML template, due to compilation.

    <script src="%PUBLIC_URL%/cpu-audio.js" async></script>

Calls from code using class must be via class="" and not className=""

The hardest part is to include controls" attribute for <audio>, as it is exposed in the public part of the DOM Shadow, but alas re-interpreted by React, trashing the native way to do it.

ReactDOM.render(
    <cpu-audio>
      <audio controls src='/blank.mp3'></audio>
    </cpu-audio>
)

is not enough.

I suppose cpu-audio starts to be integrated before audio tag is completely build. I probably need to watch on if "controls" is modified, but a lot of manipulation is done via react, missing what we really need to be exposed.

The sad but best way is to use dangerouslySetInnerHTML(), but alas....

function injectAudio() {
  return { __html: "<audio controls src='/blank.mp3'></audio>" }
}
ReactDOM.render(
  <React.StrictMode>
    <cpu-audio dangerouslySetInnerHTML={injectAudio()}></cpu-audio>
   </React.StrictMode>,
  document.getElementById('root')
)

is still not working nicely, as we can see in logs :

CPU-AUDIO: Tag <CPU-AUDIO> without <audio controls>

I really need a React specialist to work on it.

scombat commented 3 years ago

It seems to be working fine like this :

import React, { useEffect } from 'react';

export const Audio = () => {
  useEffect(() => import("../../public/vendors/cpu-audio.min.js"), []);

  return (
    <div>
      <cpu-audio>
        <audio controls src='/blank.mp3'></audio>
      </cpu-audio>
    </div>
  )
};

See my example (quick & dirty) repository and specific source code You can try it with a yarn && yarn install && yarn dev

dascritch commented 3 years ago

WOOOOW !!!! Don't you want to be correctly credited in it ? doing a examples/Call_from_Rreact.jsx ?

Thank you soooo much !

dascritch commented 3 years ago

Wonderful work from @scombat ! I think it needn't to create a <div> , simple <> globing must be enough

dascritch commented 3 years ago

A very fast placeholder, if @scombat want to complete it