reactjswysiwygstrapioembed

How to render oembed tag url


I am using a WYSIWYG plugin for Rich Text on Strapi. Adding a media url returns the following string, which I then convert to HTML using dangerouslySetInnerHTML in React.

<figure class="media">
   <oembed url="https://www.youtube.com/watch?v=dQw4w9WgXcQ"></oembed>
</figure>

But this does not render the YouTube video in the browser.

I am unsure how to go about getting this to render. Looking at oEmbed it seems in most cases that it converts to an iframe, but not sure how to do that when this comes back as a string from the HTTP request response.


Solution

  • you can use the oembed plugin provided by the WYSIWYG plugin to convert the <oembed> element to an <iframe> element.

    const MyComponent = ({ htmlString }) => {
      // Use a regular expression to find the oembed element in the HTML string
      const oembedRegex = /<oembed[^>]*>/g;
      const oembedMatch = htmlString.match(oembedRegex);
    
      // If an oembed element was found, convert it to an iframe element
      if (oembedMatch) {
        const oembedUrl = oembedMatch[0].match(/url="([^"]*)"/)[1];
        const iframeElement = `<iframe src="${oembedUrl}" frameborder="0" allow="accelerometer; autoplay; encrypted-media; gyroscope; picture-in-picture" allowfullscreen></iframe>`;
        htmlString = htmlString.replace(oembedRegex, iframeElement);
      }
    
      return <div dangerouslySetInnerHTML={{ __html: htmlString }} />;
    };