Add External Woosmap JS API in React

We currently do not provide the Woosmap JS API as a package npm. Let's see how to integrate it using custom React Hook.
  1. Create a React Hook to load External JS File
  2. Load Woosmap Loader with the hook

Create a React Hook to load External JS File

Hooks let’s access React’s state and lifecycle methods from a functional component. The useEffect Hook is a function that runs after render and every time the DOM updates. Passing in an empty array runs the effects only after the initial render. Passing in props runs effects every time the props changed.

useEffect(() => {
  console.log(`script alreadey loaded? ${scriptLoaded}`);
}, [scriptLoaded])

In our case, we would like to instantiate the Map object once the Woosmap javascript loader is fully loaded to the DOM. First, create the hook hooks/useScript.js and add the following import statements to the top of the file.


import {useEffect, useState} from 'react';

Next, load the script if not already loaded using DOM Method.


export default function useScript(src) {
  try {
    const [loaded, setLoaded] = useState(false);
      useEffect(() => {
          let script = document.querySelector(`script[src="${src}"]`);
          if (!script) {
            script = document.createElement('script');
            script.src = src;
            script.async = true;
            script.onload = function () {
          else {
      }, [src]);
      return loaded;
    } catch (err) {
        console.error(`An error occurred while loading ${src}`);

Load Woosmap Loader with the hook

Finally, you can create your Map component and load the Woosmap loader script like this:


import {useEffect} from "react";
import useScript from "./hooks/useScript";

const Map = () => {
  const woosmapLoaded = useScript("");
  useEffect(() => {
    if (woosmapLoaded) {
  }, [woosmapLoaded]);