Embed with React components

Embed with React components

The Visual Embed library for React allows you to embed ThoughtSpot components in a React application.

Before you begin🔗

Before embedding ThoughtSpot, perform the following checks:

Prepare your environment🔗

  • Check if NPM and Node.js are installed in your setup.

  • Make sure you have installed React framework and its dependencies. If React is not installed, open a terminal window and run the following command:

    npm install -g create-react-app

    For information about how to install React framework, see React documentation.

  • If you do not have a React app created for ThoughtSpot integration, create a React app and install its dependencies.

    1. To create a new React app, open a terminal window and execute the following command

      npx create-react-app ts-data-app

      In this example, the name of the app is ts-data-app.

    2. Initialize the app.

      npm start
  • Make sure a React app directory with the initial project structure is created. The app directory typically includes the following JS files:

    • Index.js

    • App.js

      To add HTML code, rename these files to .jsx. If you are building an app using TypeScript, you can rename the files to .tsx.
      For information about adding TypeScript to your existing React app project, see Adding TypeScript.

  • If you are building a multi-page app, create a Components directory and add new pages for ThoughtSpot components. To allow users to navigate between these pages, add routes in the App.tsx file.

    Note

    A functional React app may require React hooks such as useState, useRef, and useEffect. For more information about React concepts and framework, see React documentation.

Verify localhost port setting🔗

By default, React uses Port 3000 as a localhost port. Make sure you add localhost:3000 as a CSP visual embed host in the Security Settings page of the Develop tab.

If you want to use Port 8000 instead, add it to the CSP allowlist and update the following script in the package.json file in your app directory.

"scripts": {
   "start": "PORT=8000 react-scripts start",
   "build": "react-scripts build",
   "test": "react-scripts test",
   "eject": "react-scripts eject"
 }

Install SDK🔗

  • Install the Visual Embed SDK from NPM.

    npm install @thoughtspot/visual-embed-sdk

Get the GUIDs🔗

You will require GUIDs of the following objects to embed ThoughtSpot components.

  • The saved Answer or data source GUIDs to embed search and run a search query

  • Liveboard GUID to embed a Liveboard

  • Liveboard and visualization GUIDs to embed a visualization from a Liveboard

You can find the GUIDs of these objects in the UI, the developer Playground on your ThoughtSpot instance, or through the metadata/list and metadata/listobjectheaders REST API endpoints.

To embed ThoughtSpot Search page, complete the following steps:

Create a search component🔗

In your React app project, go to the Components folder in your app directory and add a page for the embedded search object; for example, Search.tsx.

  1. Import the SearchEmbed component and event libraries

    import React from 'react'
    import { Action, AuthType, init, EmbedEvent, HostEvent } from '@thoughtspot/visual-embed-sdk';
    import { SearchEmbed, useEmbedRef } from '@thoughtspot/visual-embed-sdk/react';

    If you are using Webpack 4, which is the default when using create-react-app v4, import the React components as shown in this example:

    import { SearchEmbed, useEmbedRef } from '@thoughtspot/visual-embed-sdk/lib/src/react';
  2. Initialize the SDK and specify the authentication method.

  3. Add constructor options as props

  4. Add event listeners:

    1. For Embed events, use the on<EventName> convention.

    2. For Host events, use the trigger(HostEvent.<EventName>) method.

      For more information, see EmbedEvent and HostEvent.

  5. Render the app.

    ts-data-app> npm start

Code sample🔗

import { init } from '@thoughtspot/visual-embed-sdk';
import { SearchEmbed } from '@thoughtspot/visual-embed-sdk/react';

// If you are using Webpack 4 (which is the default when using create-react-app v4), you would need to import
// the React components using the below:
import { SearchEmbed } from '@thoughtspot/visual-embed-sdk/lib/src/react';

init({
    thoughtSpotHost: '<%=tshost%>',
    authType: AuthType.None,
});

const MyComponent = ({ dataSource }) => {
    const onCustomAction = (actionEvent) => {
        // Do something with actionEvent.
    };

    return (
        <SearchEmbed
            dataSource={dataSource}
            onCustomAction={onCustomAction}
        />
    );
};

The following code sample shows additional attributes and properties:

  • A Search function with a data source ID.

  • The searchOptions property to construct a query string with [quantity purchased] [region] keywords and execute the search query.

  • Event handlers for init and Load` events.

    import { init } from "@thoughtspot/visual-embed-sdk";
    import { SearchEmbed } from "@thoughtspot/visual-embed-sdk/react";
    
    // If you are using Webpack 4 (which is the default when using create-react-app v4), you would need to import
    // the React components using the below:
    import { SearchEmbed } from "@thoughtspot/visual-embed-sdk/lib/src/react";
    
    init({
      thoughtSpotHost: "<%=tshost%>",
      authType: AuthType.None,
    });
    const Search = () => {
      //To construct a search query and execute the search, define a search token string
      const searchOptions = {
        searchTokenString: "[quantity purchased] [region]",
        executeSearch: true,
      };
      //add event handlers
      const onInit = () => {
        console.log(EmbedEvent.Init, {});
      };
      const onLoad = () => {
        console.log(EmbedEvent.Load, {});
      };
      return (
        <SearchEmbed
          frameParams={{
            height: 600,
          }}
          dataSource={["cd252e5c-b552-49a8-821d-3eadaa049cca"]}
          searchOptions={searchOptions}
          onLoad={onLoad}
        />
      );
    };

For more information about SearchEmbed objects and attributes, see the following pages:

Test your app🔗

  • Load your application.

  • Check if the ThoughtSpot search bar is rendered with the search tokens you specified.

    embed search react

Embed a Liveboard🔗

To embed a ThoughtSpot Liveboard, complete the following steps:

Create a Liveboard component🔗

In your React app project, go to the Components directory and add a new page for Liveboard in your app directory; for example, liveboard.tsx.

  1. Import the LiveboardEmbed component and event libraries:

    import React from "react";
    import {
      Action,
      init,
      EmbedEvent,
      HostEvent,
      RuntimeFilterOp,
    } from "@thoughtspot/visual-embed-sdk";
    import { LiveboardEmbed, useEmbedRef } from "@thoughtspot/visual-embed-sdk/react";

    If you are using Webpack 4, import the React components as shown in this example:

    import { LiveboardEmbed, useEmbedRef } from '@thoughtspot/visual-embed-sdk/lib/src/react';
  2. Specify the authentication method.

  3. Add constructor options as props.

    1. For Embed events, use the on<EventName> convention.

    2. For Host events, use the trigger(HostEvent.<EventName>) method.

      For more information, see EmbedEvent and HostEvent.

  4. Render the app.

    ts-data-app> npm start

Code sample🔗

The following code sample embeds a Liveboard, disables UI actions such as Share and Delete, sets specific visualization GUIDs as visible visualizations, and registers event handlers for Init,Load, SetVisibleVizs, onLiveboardRendered, and VizPointDoubleClick.

import { init } from '@thoughtspot/visual-embed-sdk';
import { LiveboardEmbed } from '@thoughtspot/visual-embed-sdk/react';

// If you are using Webpack 4 (which is the default when using create-react-app v4), you would need to import
// the React components using the below:
import { LiveboardEmbed } from '@thoughtspot/visual-embed-sdk/lib/src/react';

init({
    thoughtSpotHost: '<%=tshost%>',
    authType: AuthType.None,
});

const Liveboard = ({liveboardId}) => {
   const ref = useEmbedRef<typeof LiveboardEmbed>();
    //apply runtime filters
   const runtimeFilters = [
      {
        columnName: "state",
        operator: RuntimeFilterOp.EQ,
        values: ["michigan"],
      },
    ];
   const onLoad = () => {
   console.log(EmbedEvent.Load, {});
   };
   //Register an event handler to trigger the SetVisibleVizs event when the Liveboard is rendered
    const onLiveboardRendered = () => {
      embedRef.current.trigger(HostEvent.SetVisibleVizs, [
         "3f84d633-e325-44b2-be25-c6650e5a49cf",
         "28b73b4a-1341-4535-ab71-f76b6fe7bf92",
        ]);
      };
   return (
    <LiveboardEmbed
        frameParams={{
            height: 400,
        }}
        ref={embedRef}
        liveboardId="d084c256-e284-4fc4-b80c-111cb606449a"
        runtimeFilters={runtimeFilters}
        onLoad={onLoad}
        onLiveboardRendered={onLiveboardRendered}
    />
  );
};

For more information about LiveboardEmbed object and properties, see the following pages:

Test your app🔗

  • Load the embedded Liveboard in your app.

  • Check if the registered events are triggered and logged in the console.

    liveboard embed react

Embed a visualization🔗

To embed a ThoughtSpot Liveboard, complete the following steps:

Create a visualization component🔗

In your React app project, go to the Components folder in your app directory and add a new page for visualization; for example, viz.tsx.

  1. Import the LiveboardEmbed component and event libraries:

    import React from "react";
    import {
      Action,
      init,
      EmbedEvent,
      HostEvent,
      RuntimeFilterOp,
    } from "@thoughtspot/visual-embed-sdk";
    import { LiveboardEmbed, useEmbedRef } from "@thoughtspot/visual-embed-sdk/react";

    If you are using Webpack 4, import the React components as shown in this example:

    import { LiveboardEmbed, useEmbedRef } from '@thoughtspot/visual-embed-sdk/lib/src/react';
  2. Initialize the SDK and specify the authentication method.

  3. Add constructor options as props.

    1. For Embed events, use the on<EventName> convention.

    2. For Host events, use the trigger(HostEvent.<EventName>) method.

      For more information, see EmbedEvent and HostEvent.

  4. Render the app.

    ts-data-app> npm start

Code sample🔗

The following example includes the viz function with the Liveboard and visualization GUIDs and registers event handlers for Init and Load.

import { init } from '@thoughtspot/visual-embed-sdk';
import { LiveboardEmbed } from '@thoughtspot/visual-embed-sdk/react';

// If you are using Webpack 4 (which is the default when using create-react-app v4), you would need to import
// the React components using the below:
import { LiveboardEmbed } from '@thoughtspot/visual-embed-sdk/lib/src/react';

init({
    thoughtSpotHost: '<%=tshost%>',
    authType: AuthType.None,
});
const vizEmbed = ({liveboardId}) => {
    const viz = ({ vizId }) => {
    // Register event handlers
    const onLoad = () => {
    console.log(EmbedEvent.Load, {});
    };
   };
   return (
     <LiveboardEmbed
        frameParams={{
          height: 400,
        }}
        liveboardId="d084c256-e284-4fc4-b80c-111cb606449a"
        vizId="3f84d633-e325-44b2-be25-c6650e5a49cf"
        onLoad={onLoad}
     />
   );
};

For more information about visualization objects and its properties, see the following pages:

Test your app🔗

  • Verify if the embedded visualization is rendered correctly.

  • Check if the registered events are triggered and logged in the console.

    viz embed react
  • Check if the registered events are emitted and logged in the console.

Embed full app🔗

To full ThoughtSpot application, complete the following steps:

Create a full app component🔗

In your React app project, go to the Components folder in your app directory and add a new page for full application embed: for example, fullApp.tsx.

  1. Import the AppEmbed component and event libraries:

    import React from "react";
    import {
      Action,
      init,
      EmbedEvent,
      HostEvent,
      Page
    } from "@thoughtspot/visual-embed-sdk";
    import { AppEmbed, useEmbedRef } from '@thoughtspot/visual-embed-sdk/react';

    If you are using Webpack 4, import the React components as shown in this example:

    import { AppEmbed, useEmbedRef } from '@thoughtspot/visual-embed-sdk/lib/src/react';

    Note that the import includes Page. The Page enumeration is required to set a specific ThoughtSpot page as a home tab when the application loads.

  2. Initialize the SDK and specify the authentication method.

  3. Add constructor options as props.

    1. For Embed events, use the on<EventName> convention.

    2. For Host events, use the trigger(HostEvent.<EventName>) method.

      For more information, see EmbedEvent and HostEvent.

  4. Render the app.

    ts-data-app> npm start

Code sample🔗

The following example includes a FullApp function with the Page.Home set as the default tab and registers event handlers for Init and Load.

const FullApp = () => {
  // Register event handlers
  const onLoad = () => {
    console.log(EmbedEvent.Load, {});
  };
  return (
    <AppEmbed
      frameParams={{
        height: 600,
      }}
      pageId={Page.Home}
      onLoad={onLoad}
    />
  );
};

For a complete list of AppEmbed attributes and events, see the following pages:

Test your app🔗

  • Load your application.

  • Check if the default home page is the same as you defined in the pageId attribute.

    full app react
  • Check if the registered events are emitted.

Add routes for navigation🔗

If your app has multiple pages and you have created a new page for the embedded ThoughtSpot component, make sure you add a route in your app for navigation.

The following example shows a route for the Liveboard page.

import { Route, Routes} from "react-router-dom";
import { Liveboard } from './components/liveboard'
function App() {
 return (
   <div className="App">
     <Routes>
       <Route path="/" element={<h1>Home</h1>} />
       <Route path="/liveboard" element={<Liveboard />} />
       <Route path="/about" element={<About />} />
     </Routes>
   </div>
 );
}
export default App;