3

I am using a tawk.io chat on my reactjs app:- This is content of my index.js file:-

import React from "react";
import ReactDOM from "react-dom";
import App from "./App";
import { BrowserRouter, Switch, Route } from "react-router-dom";
import BookRead from "./pages/BookRead";

ReactDOM.render(
  <React.StrictMode>
    <BrowserRouter>
      <Switch>
        <Route exact path="/view/:id/:section/:part" component={BookRead} />
        <Route component={App} />
      </Switch>
    </BrowserRouter>
  </React.StrictMode>,
  document.getElementById("root")
);

App.js component file content :-

import React, { useEffect, useState } from "react";
import { Route } from "react-router-dom";
import Login from "./pages/Login";
import Account from "./pages/Account";
import Contact from "./pages/Contact";
import Home from "./pages/Home";

function App(props) {

  useEffect(() => {
    var Tawk_API = Tawk_API || {},
      Tawk_LoadStart = new Date();
    (function () {
      var s1 = document.createElement("script"),
        s0 = document.getElementsByTagName("script")[0];
      s1.async = true;
      s1.src = "https://embed.tawk.to/5a624e/default";
      s1.charset = "UTF-8";
      s1.setAttribute("crossorigin", "*");
      s0.parentNode.insertBefore(s1, s0);
    })();
  }, []);

  return (
    <div className="content">
      <div className="container">
        <Route exact path="/" component={Home} />
        <Route path="/contact-us" component={() => <Contact user={user} />} />
          )}
        />
        <Route path="/account" component={Account} />
      </div>
    </div>
  );
} 
export default App;

How can i show the chat widget in all components inside the App.js route and hide/remove it from the route <Route exact path="/view/:id/:section/:part" component={BookRead} /> ?

Q8root
  • 1,243
  • 3
  • 25
  • 48

2 Answers2

6

Solved by adding the following to BookRead.js component :-

useEffect(() => {
    if (window.Tawk_API) {
      window.Tawk_API.hideWidget();
    }
    return () => {
      if (window.Tawk_API) {
        window.Tawk_API.showWidget();
      }
    };
  }, []);
Q8root
  • 1,243
  • 3
  • 25
  • 48
0

The API docs at https://developer.tawk.to/jsapi/ suggest you could use Tawk_API.showWidget(); and Tawk_API.hideWidget(); to show and hide the widget.

React-Router provides an useLocation hook you can use to figure out when the location has changed.

Put those two together and you should be able to get the effect you want.

AKX
  • 152,115
  • 15
  • 115
  • 172
  • Can you show me where can i use Tawk_API.hideWidget(), if the chat widget is initiated on App.js and the route where i want to hide the chat widget is in index.js – Q8root Sep 26 '20 at 10:37