Search code examples
reactjsembed

How to embed an HTML/script snippet into a react.js page without jQuery?


I created a react website using create-react-app. In one of the pages, I want to embed an airbnb preview, see below code and screenshot provided by airbnb.

How can I insert this code into my React components? (NB I don't want to use jQuery)

<div
  class="airbnb-embed-frame"
  data-id="21917882"
  data-view="home"
  data-hide-price="true"
  style="width:450px;height:300px;margin:auto"
>
  <a href="https://www.airbnb.com/rooms/21917882?s=51">
    <span>View On Airbnb</span>
  </a>
  <a 
    href="https://www.airbnb.com/rooms/21917882?s=51" 
    rel="nofollow"
    >T2 hypercentre Capitole/St-Sernin, quiet &amp; bright
  </a>
  <script async="" src="https://www.airbnb.com/embeddable/airbnb_jssdk" />
</div>;

The component created by this code, which I want to embed in the react page


Solution

  • This does go quite against React principles, but you could load the embed script with something like react-async-script-loader (or a custom solution) and then call the provided AirbnbAPI.bootstrap() function on render or when the component mounts.

    💻 Live Example

    import React, { Component } from "react";
    import scriptLoader from "react-async-script-loader";
    
    const Preview = ({ isScriptLoaded, isScriptLoadSucceed }) => {
      if (isScriptLoaded && isScriptLoadSucceed) {
        window.AirbnbAPI.bootstrap();
      }
    
      return (
        <div
          className="airbnb-embed-frame"
          data-id="21917882"
          data-view="home"
          data-hide-price="true"
          style={{ width: 450, height: 300, margin: "auto" }}
        >
          <a href="https://www.airbnb.com/rooms/21917882?s=51">
            <span>View On Airbnb</span>
          </a>
          <a href="https://www.airbnb.com/rooms/21917882?s=51" rel="nofollow">
            T2 hypercentre Capitole/St-Sernin, quiet &amp; bright
          </a>
        </div>
      );
    };
    
    export default scriptLoader(["https://www.airbnb.com/embeddable/airbnb_jssdk"])(
      Preview
    );