javascripthtmlreactjswebpacknext.js

How to convert my Chatbot component to <script> tag so that anyone can use it in their website with that <script>, in React.js?


I have a working Chatbot component in my Next.js application.

My application screen Now I to make a functionality that anyone can use this component (integrate it) in their own website using tag of this component.

I have tried to place my ChatbotComponent inside a Bot.js file and try to render it like this:

function ChatbotComponent() {
  return (
    // Your chatbot component JSX goes here
    <div>
      <h1>Chatbot Content</h1>
      {/* Additional chatbot UI */}
    </div>
  );
}

function renderChatbot() {
  const container = document.createElement('div');
  document.body.appendChild(container);

  ReactDOM.render(<ChatbotComponent />, container);
}

renderChatbot()

And after that I made a new project and use this file in as:

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Document</title>
    <script src="http://localhost:3000/Bot.js" defer></script>
  </head>
  <body></body>
</html>

But it shows error like this enter image description here

I think its because the React file is not converted into browsers readable JavaScript code.

Please tell my what am I doing wrong and how can I implement this functionality.


Solution

  • You did everything correct

    but instead of rendering the localhost url, you can run the build file

    1. modify your package.json like this

    "build": "react-scripts build && mv build/static/js/main*.js build/static/js/main.chatbotfile.js",

    1. Run npm run build and

    2. Attach this code to any file you want (ex. html boiler file)

    <script
      id="crmone-chatbot"
      chatbotId=""
      src="build/static/js/main.chatbotfile.js"
    ></script>
    

    (attach any css file also if any)

    Note: you can toggle your index.js as if you want to run your chatbot in local or want to build for script tag like this

    function renderChatbot() {
      const container = document.createElement("div");
      container.style.position = "relative";
      container.style.height = "calc(100% - 16px)";
      container.style.width = "100%";
      container.style.zIndex = "9999";
    
      document.body.appendChild(container);
    
      ReactDOM.createRoot(container).render(<App />);
    }
    
    if (runInLocal || false)
      ReactDOM.createRoot(document.getElementById("root") as HTMLElement).render(
        <React.StrictMode>
          <App />
        </React.StrictMode>
      );
    else renderChatbot();