javascriptreactjstawk.to

Making the chat widget Tawk.io disappear on one component


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} /> ?


Solution

  • 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();
          }
        };
      }, []);