I am trying to embed an external map service into my React app. Their recommendation to integrate the API into a regular HTML web page looks like this:
<script type="text/javascript" src="//map.search.ch/api/map.js"></script>
<script type="text/javascript">new SearchChMap({center:[123456,987654],y:"-1m",poigroups:"default"});</script>
I tried to apply this in my typescript
React component as follows:
declare class SearchChMap {
constructor(_: {})
}
// ...
<>
<script type="text/javascript" src="//map.search.ch/api/map.js"></script>
<script type="text/javascript">{new SearchChMap({ center: [123456, 987654], poigroups: "default" })}</script>
{/* ... */}
</>
While this compiles, I receive the following runtime error: ReferenceError: SearchChMap is not defined
.
What is the correct way of using legacy JavaScript classes from an externally hosted script in your React components?
Update:
I tried this answer to no avail, using the following code:
componentDidMount(): void {
const script1: HTMLScriptElement = document.createElement("script");
script1.src = "//map.search.ch/api/map.js";
script1.async = true;
document.body.appendChild(script1);
const script2: HTMLScriptElement = document.createElement("script");
script2.text = 'new SearchChMap({center:[123456,987654],y:"-1m",poigroups:"default"});';
script2.async = true;
document.body.appendChild(script2);
}
This results in the exact same error message, just a few seconds later, since the scripts are added dynamically.
Update 2:
Moving the object creation to onload
as suggested by AWolf
did the trick:
componentDidMount(): void {
const scriptTag: HTMLScriptElement = document.createElement("script");
scriptTag.src = "//map.search.ch/api/map.js";
document.head.appendChild(scriptTag);
scriptTag.onload = () => {
new SearchChMap({ center: this.props.center, container: this.props.containerId });
};
}