3

on one of my components I have an external widget which requires a script tag and a special div element. Once the page loads the script inserts an iframe inside the div.

The issue I am having is that the widget only works when the page is loaded like a normal http page. This widget works when I use anchor tags however with Link it doesn't as there is no page load.

List component ----Link----> Property component

How can I achieve the same behavior but with Link?

App.js

    <Switch> 
        <Route path="/" exact component={Home} />
        <Route path="/list" exact component={List} />
        <Route path="/property/:id/:sleeps/:start/:end" exact component={Property} />
        <Route component={Error} />
    </Switch>

List.js

<Link to={`/property/${property.id}/${property.sleeps}/${property.start}/${property.end}`}>
    <img src={property.image} alt={property.name}/>
</Link>

Property.js

componentDidMount = () => {
    //function inserts script to body
    this.loadScript('https://widgetSite.co.uk/components/embed.js');
}

//inside render
<div
    data-calendar-key="widget key"
    data-calendar-property-id={this.propID}
    id="calendar-js">
    Your widget will appear here.
</div>
Sai
  • 801
  • 3
  • 10
  • 27

2 Answers2

1

Here is a basic example of React Portals.

Index.html

<body>
  <div id="root"></div>
  <div id="my-widget"></div>
</body>

MyWidget Component

import React, { Component } from 'react';
import ReactDOM from 'react-dom';

const Widget = document.getElementById('my-widget');

class MyWidget extends Component {
  state = { openWidget: false };

 //functions to open close widget

  render() {
    return ReactDOM.createPortal(this.renderWidget(), Widget);
  }

  renderWidget() { /*add your widget elements*/ }
}

export default MyWidget;

You can now use the MyWidget component. Hope this helps. Thanks!

Ray
  • 325
  • 1
  • 5
  • 15
  • Thanks Ray, but I looked into it and unfortunately, I don't think this is what solves it. My issue is that when moving to the property page with Link the widget script is not sending it's GET requests. – Sai Sep 12 '19 at 09:48
-1

Try to implement something like this How to force a script reload and re-execute? in your loadScript function so your script will be force to re-load, re-execute and grab the right data-* every time componentDidMount is trigger. I hope this help