Search code examples
javascriptreactjs

How do I trigger an external vanilla JS function from within a React component?


I am building an application in React and placing it on a page on my site.

I have a 3rd party chat widget/plugin on my site and would like it to be activated when a particular button is clicked from within my React component. In vanilla JS this is usually done with the following function:

LiveChat.openChatWindow();

However, I cannot figure out now to call this function from within my react component.

I've tried

  const launchChat = () => {
    LiveChat.openChatWindow();
  }
// Other code

  <a class="btn chat-btn" onClick={launchChat}>Chat to us</a>

But the application wont compile because, of course, LiveChat is not defined (on my local machine).

I cannot seem to launch the chat by detecting a click from outside the component either, because, of course, the button is created by React, and not in the DOM.

$(function(){
  $(".chat-btn").click(function(){
    LiveChat.openChatWindow();
  });
});

Would anyone know how I should be going about this?


Solution

  • You can grant the LiveChat to window scope and in React component just access it from window.

    This is the example code:

    1. Where you declared the LiveChat variable
    window.LiveChat = ...
    
    1. In the react component
    const launchChat = () => {
      window.LiveChat.openChatWindow();
    }