Knit UI Component with ReactJS

Import the web component in your html file

Firstly we need to import the web component through JS file link using a

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <link rel="icon" type="image/svg+xml" href="/vite.svg" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Knit + React</title>
    <script type="module" src="https://af1.getknit.dev/knit-ui-comp.js"></script>
  </head>
  <body>
    <div id="root"></div>
    <script type="module" src="/src/main.tsx"></script>
  </body>
</html>

πŸ“˜

Make sure to import the web component script as a module

Make sure to include type="module" in the script tag.

Declare the web component in your application

Declare the component and attach functions for custom events emitted from the knit-auth component.

import { useEffect, useRef } from "react";

function App() {
  const knitRef = useRef(null);
  // Backend call to generate & get the authSessionToken
  const newSessionFn = (e) => {
    e?.preventDefault();
    // Hit the backend to generate authSessionToken
        fetch('https://yourbackend.com/getSessionToken', {method:"GET"}).then(res=> res.json())
 	    .then((r) => {
        // UI Auth component won't open with a empty session token
        knitRef?.current?.setAttribute("authsessiontoken", r.msg.token);
        // Set skipIntro attribute to disable the introduction screen
        // knitRef?.current?.setAttribute("skipIntro",'');
      })
      .catch((err) => {
        console.error(err);
      });
  };
  
  // Upon finishing the integration flow
  const onFinishFn = (e) => {
    e.preventDefault();
  // integrationDetails is emitted through onFinish event
    console.log( e["detail"]["integrationDetails"]);
  // Set skipIntro attribute to disable the introduction screen
  // knitRef?.current?.setAttribute("skipIntro",'');
  };
  
  // Upon deactivate of integration
  const onDeactivateFn = (e) => {
    e.preventDefault();
    console.log( e["detail"]["integrationDetails"]);
  };
  
  // Upon closing of the knit-auth component
  const onKnitCloseFn = (e) => {
    e.preventDefault();
    console.log( e["detail"]["knitClosed"]);
  };
  
  useEffect(() => {
     // Assign functions to event listeners for onNewSession and onFinish events.
    knitRef.current?.addEventListener("onNewSession", newSessionFn);
    knitRef.current?.addEventListener("onFinish",onFinishFn);
    knitRef.current?.addEventListener("onDeactivate",onDeactivateFn);
    knitRef.current?.addEventListener("onKnitClose",onKnitCloseFn);
    // Set the token once the component has mounted
   newSessionFn();
    return () => {
    // Remove events listeners on unmount
      knitRef.current?.removeEventListener("onNewSession", newSessionFn);
      knitRef.current?.removeEventListener("onFinish",onFinishFn);
      knitRef.current?.removeEventListener("onDeactivate",onDeactivateFn);
      knitRef.current?.removeEventListener("onKnitClose",onKnitCloseFn);
    };
  }, []);

  return (
    <knit-auth ref={knitRef}>
      <button slot="trigger">Open Knit</button>
    </knit-auth>
  );
};

export default App;
import { useEffect, useRef } from "react";

function App() {
  const knitRef = useRef<HTMLElement>(null);
  // Backend call to generate & get the authSessionToken
  const newSessionFn = (e?: CustomEvent) => {
    e?.preventDefault();
    // Hit the backend to generate authSessionToken
        fetch('https://yourbackend.com/getSessionToken', {method:"GET"}).then(res=> res.json())
      .then((r) => {
        // UI Auth component won't open with a empty session token
        knitRef?.current?.setAttribute("authsessiontoken", r.msg.token);
        // Set skipIntro attribute to disable the introduction screen
        // knitRef?.current?.setAttribute("skipIntro",'');
      })
      .catch((err: any) => {
        console.error(err);
      });
  };

  // Upon finishing the integration flow
  const onFinishFn = (e: CustomEvent) => {
    e?.preventDefault();
    console.log(e["detail"]["integration-id"]);
  };
	
	// Upon deactivate of integration
  const onDeactivateFn = (e: CustomEvent) => {
    e?.preventDefault();
    console.log(e["detail"]["integrationDetails"]);
  };

  // Upon closing of the knit-auth component
  const onKnitCloseFn = (e: CustomEvent) => {
    e?.preventDefault();
    console.log(e["detail"]["knitClosed"]);
  };

  useEffect(() => {
    // Assign functions to event listeners for onNewSession and onFinish events.
    knitRef.current?.addEventListener("onNewSession", newSessionFn as EventListener);
    knitRef.current?.addEventListener("onFinish", onFinishFn  as EventListener);
    knitRef.current?.addEventListener("onDeactivate", onDeactivateFn as EventListener);
    knitRef.current?.addEventListener("onKnitClose", onKnitCloseFn as EventListener);
    // Set the token once the component has mounted
    newSessionFn();

    return () => {
      // Remove events listeners on unmount
      knitRef.current?.removeEventListener("onNewSession", newSessionFn as EventListener);
      knitRef.current?.removeEventListener("onFinish", onFinishFn as EventListener);
      knitRef.current?.removeEventListener("onDeactivate", onDeactivateFn as EventListener);
      knitRef.current?.removeEventListener("onKnitClose", onKnitCloseFn as EventListener);
    };
  }, []);

  return (
    <knit-auth ref={knitRef}>
      <button slot="trigger">Open Knit</button>
    </knit-auth>
  );
}

export default App;

Declare types for knit-auth web component (Typescript)

Create a new file or include the following snippet in the declaration file.

  namespace JSX {
    interface IntrinsicElements {
      "knit-auth": any;
    }
  }

Things to consider:

  • Pass any element ( preferably a button ) as a child to the knit-auth element, with slot="trigger attribute. This element will open the UI Auth component when clicked.
  • Pass session token that you received from your backend to the knit-auth element through authsessiontoken attribute.
  • Assign functions to onNewSession, onFinish, onDeactivate and onKnitClose events emitted from the knit-auth component. onNewSession should call your backend to get a new auth session token, if need be.
  • If you want to disable the introduction screen, set skipIntro attribute to true.
  • Upon completion of the integration setup flow, an integrationDetails object is emitted through the onFinish event, you can access the integrationDetails using e['detail']['integrationDetails'].
  • Upon deactivation of the integration, an integrationDetails object is emitted through the onDeactivate event, you can access the integrationDetails using e['detail']['integrationDetails'].
  • Upon closing of the knit-auth component, onKnitClose event is emitted.

What’s Next