How to call thrid party javascript functions in ReactJS

Viewed 49

I have a third party javascript file app.js which contains the below snippet

(function ($) {
    "use strict";

    // json for properties markers on map
    var props = [];

    // custom infowindow object
    var infobox = new InfoBox({
        disableAutoPan: false,
        maxWidth: 202,
        pixelOffset: new google.maps.Size(-101, -285),
        zIndex: null,
        boxStyle: {
            background: "url('images/infobox-bg.png') no-repeat",
            opacity: 1,
            width: "202px",
            height: "245px"
        },
        closeBoxMargin: "28px 26px 0px 0px",
        closeBoxURL: "",
        infoBoxClearance: new google.maps.Size(1, 1),
        pane: "floatPane",
        enableEventPropagation: false
    });

    // function that adds the markers on map
    var addMarkers = function (props, map) {}
    
    })(jQuery)

currently am loading the script using the below steps

 loadScript(src) {
        const script = document.createElement("script");
        script.src = src;
        script.async = false;
        document.body.appendChild(script);
    }

and

this.loadScript('js/app.js');

but now I want away to access the function addMarkers from the reactJS component, it seems window.functionName won't work, so how can I achieve that ?

Note : app.js is being loaded in other components too

2 Answers

You can't, that function is defined inside the closure of a self executing function. The point of using self executing functions like this is to stop the local variables polluting the window namespace.

The fact that jQuery is passed in as a parameter makes it look like this script creates a jQuery plugin but you have only posted a snippet of the code. If it is a jQuery plugin you would usually access it via the jQuery object or it's shortcut $ object but there is not enough info in your question to know.

On a side note it is usually frowned upon to mix jQuery with modern frameworks such as React. Are you sure you need this script to do what you want? Can you not call the Google Maps API directly to remove the need for jQuery?

In order to achieve my requirement I had to initialize a global variable in react component and then access it from the javascript function after some timeout, not the best ... but the only way I found

componentDidMount(){
window.properties=[] //global variable accessible from 3rd party JS file
 this.setState({ property: this.props.location.property }, () => {
   propertyService.incView(this.state.property.property_id)
    window.properties.push(this.state.property)
 })
}

and in the third-party javascript file I loop on the properties array and process them as required

Related