DEV Community

Cover image for Tour guide / product tour a zero-dependency that works in React, Vue, Svelte, Angular, Electron and Android / React Native WebViews
Elmer Alluad Jr.
Elmer Alluad Jr.

Posted on

Tour guide / product tour a zero-dependency that works in React, Vue, Svelte, Angular, Electron and Android / React Native WebViews

Every app eventually needs an onboarding tour. "Here's the search bar. Here's your profile. Click here to create your first project."

It sounds simple. Then you try to build one:

  • The popover runs off the edge of the screen on a phone.
  • The highlighted button sits inside a menu that isn't open yet.
  • Your app's CSS breaks the tour's layout, or the tour's CSS breaks your app.
  • Keyboard and screen reader users get stuck inside it, or can't reach it at all.
  • The library you picked only supports one framework, and your company runs three.

I hit all of these, so I built @xkid1/tour-guide: a product-tour Web Component with zero runtime dependencies. You write <tour-guide> once and it runs in plain HTML, React, Vue, Svelte, Angular, Electron, and Android / iOS / React Native WebViews.

Desktop demo: a tour steps through a dashboard, opens a menu with its own tour, and scrolls smoothly to the footer

The 30-second version

npm i @xkid1/tour-guide
Enter fullscreen mode Exit fullscreen mode
<script type="module">
  import '@xkid1/tour-guide/browser';
</script>

<tour-guide id="tour" theme="auto">
  <tour-step title="Welcome 👋">A quick tour of the essentials.</tour-step>
  <tour-step target="#search" title="Search" placement="bottom">
    Find anything here.
  </tour-step>
  <tour-step target="#profile" title="Profile">
    Manage your <strong>account</strong>.
  </tour-step>
</tour-guide>

<button onclick="document.getElementById('tour').start()">Start tour</button>
Enter fullscreen mode Exit fullscreen mode

That's a working tour, with no JavaScript config. The page dims around each target, the popover sits next to it, and the user moves through it with buttons, the arrow keys, or Esc.

No bundler? Use the script tag:

<script src="https://cdn.jsdelivr.net/npm/@xkid1/tour-guide@0/dist/browser/tour-guide.iife.js"></script>
<script>
  TourGuide.createTour({
    steps: [{ title: 'Hello!', content: 'This page has a tour.' }],
  }).start();
</script>
Enter fullscreen mode Exit fullscreen mode

Why a Web Component?

A custom element is the one UI primitive that every framework already understands. Building the tour as <tour-guide> instead of a React component or a Vue plugin gives a few things for free:

  • One implementation everywhere. Your marketing site (plain HTML), your dashboard (React) and your admin panel (Angular) all ship the same tour, with the same behaviour and the same bugs fixed once.
  • Shadow DOM isolation. The tour's styles never leak into your app, and your global CSS never breaks the tour.
  • It still themes easily. Isolation doesn't lock you out: you style it with --tg-* CSS variables and ::part().
tour-guide {
  --tg-primary: #7c3aed;
  --tg-popover-radius: 16px;
  --tg-font-family: 'Inter', sans-serif;
}
tour-guide::part(complete-button) {
  background: #16a34a;
}
Enter fullscreen mode Exit fullscreen mode

Zero dependencies, for real

The package has no dependencies and no peerDependencies. CI enforces that.

So how do the React and Vue adapters work without importing React or Vue? You pass your framework in:

import * as React from 'react';
import { createReactTourGuide } from '@xkid1/tour-guide/react';

const { TourGuide, useTourGuide } = createReactTourGuide(React);

export function App() {
  const [open, setOpen] = React.useState(false);

  return (
    <>
      <button onClick={() => setOpen(true)}>Start tour</button>
      <TourGuide
        open={open}
        steps={[
          { id: 'intro', title: 'Welcome' },
          { target: '#search', title: 'Search', content: 'Find anything.' },
        ]}
        theme="auto"
        onEnd={() => setOpen(false)}
      >
        {/* Real React components inside a step */}
        <div slot="step-intro">
          <MyIntro />
        </div>
      </TourGuide>
    </>
  );
}
Enter fullscreen mode Exit fullscreen mode

Because the adapter uses your copy of React, the package can never add a second React to your bundle or fight you over versions. The same pattern covers Vue 3 (createVueTourGuide(Vue), with v-model:open). Svelte 3–5 needs no injection at all, since its adapter is an action:

<tour-guide use:tourGuide={{ steps, open, theme: 'auto' }}></tour-guide>
Enter fullscreen mode Exit fullscreen mode

Angular 15+ gets registerTourGuide() and a small chainable TourGuideController.

The whole browser bundle, element and adapters included, is about 16 KB gzipped.

The hard parts it handles for you

Tours that open menus and wait for data

Real tours point at things that don't exist yet: a dropdown item, a modal, a row that loads from an API. Every step has async hooks, and the tour waits for them:

{
  target: '#menu-billing',
  title: 'Billing',
  content: 'Plans and invoices live here.',
  beforeShow: async () => {
    openUserMenu();
    await new Promise(requestAnimationFrame); // let it render before measuring
  },
  beforeLeave: () => closeUserMenu(),
}
Enter fullscreen mode Exit fullscreen mode

A target can also be a function, resolved each time the step shows, so it finds elements created after the page loaded.

Your bugs can't break the tour

If a hook, a content() function or a target() function throws, the move is cancelled, the current step stays on screen, and a tour-error event fires with a TourGuideError (a stable code, plus the phase and step it failed in). A broken onboarding flow should never leave a user stuck under a dark overlay.

Typos get caught too. Steps and options are checked as you use them:

WARN  [tour-guide] Unknown option "clsoeOnEsc". Did you mean "closeOnEsc"?
WARN  [tour-guide] step 2 ("billing"): target "#billing" was not found, so the step is centred.
Enter fullscreen mode Exit fullscreen mode

It works on phones

The popover flips and clamps to stay on screen. Below a breakpoint it becomes a screen-wide card that follows its target, and it falls back to a bottom sheet when there's no room. It also repositions when the on-screen keyboard opens and respects safe-area insets.

Mobile demo: the popover becomes a screen-wide card that follows each highlighted element

It's accessible by default

  • The popover is a modal role="dialog", named by the step title
  • Focus moves in, Tab stays inside, and focus returns where it was when the tour ends
  • Esc closes it and ← / → navigate (but not while you're typing in a field)
  • Progress is announced to screen readers
  • 44px touch targets on mobile
  • prefers-reduced-motion turns off animations and smooth scrolling, and forced-colours mode is respected

It's safe by default

Strings render as text, so user data in a step can't inject markup. HTML needs an explicit allowHtml: true. Styles load through constructable stylesheets, so it runs under a strict Content Security Policy (style-src 'self') with no 'unsafe-inline'. That matters a lot in Electron apps.

Beyond the browser: Electron, Android and React Native

Electron

Import @xkid1/tour-guide/electron in the renderer process. It works with contextIsolation: true and nodeIntegration: false, and because the styles go through constructable stylesheets, you don't have to add 'unsafe-inline' to your CSP.

import { createTour } from '@xkid1/tour-guide/electron';
createTour({ steps }).start();
Enter fullscreen mode Exit fullscreen mode

Android and React Native (WebView)

A lot of mobile apps are partly web: a help centre, a settings page or a whole hybrid screen running in a WebView. Those screens need onboarding too, and the native app usually wants to know how it went.

<tour-guide> runs in any modern Android System WebView and iOS WKWebView. Load the single-file script build, then call connectNativeBridge(). It's a two-way channel:

  • Web → native: every tour event is sent to the app as JSON, such as {"source":"tour-guide","type":"tour-end","reason":"complete","index":2,"total":3}. Only ids and indexes cross the bridge. Functions and DOM nodes are dropped.
  • Native → web: the app posts { "command": "next" } back. Commands are start, next, back, goTo (with index), skip, complete, close and refresh, and anything else is ignored.

It works out which side it's running on: window.ReactNativeWebView, an Android @JavascriptInterface named AndroidTour, or the iOS handler webkit.messageHandlers.tourGuide.

React Native with react-native-webview:

import { useRef } from 'react';
import { WebView } from 'react-native-webview';

const html = `<!doctype html>
<html>
  <head>
    <meta name="viewport" content="width=device-width, initial-scale=1, viewport-fit=cover" />
    <script src="https://cdn.jsdelivr.net/npm/@xkid1/tour-guide@0.1.0/dist/browser/tour-guide.iife.js"></script>
  </head>
  <body>
    <button id="profile">Profile</button>
    <tour-guide id="tour"></tour-guide>
    <script>
      const tour = document.getElementById('tour');
      tour.steps = [
        { target: '#profile', title: 'Your profile', content: 'Manage your account here.' },
        { title: 'All set', content: 'Enjoy the app!' },
      ];
      TourGuide.connectNativeBridge(tour, {
        acceptMessage: (event) => event.origin === '' || event.origin === location.origin,
      });
    </script>
  </body>
</html>`;

export function TourScreen() {
  const webview = useRef<WebView>(null);
  const send = (command: string, index?: number) =>
    webview.current?.postMessage(JSON.stringify({ command, index }));

  return (
    <WebView
      ref={webview}
      originWhitelist={['*']}
      source={{ html }}
      onLoadEnd={() => send('start')}
      onMessage={(e) => {
        const msg = JSON.parse(e.nativeEvent.data);
        if (msg.type === 'tour-end') {
          console.log('Tour finished with', msg.reason); // save it, send it to analytics…
        }
      }}
    />
  );
}
Enter fullscreen mode Exit fullscreen mode

Native Android (Kotlin). Copy tour-guide.iife.js into app/src/main/assets/ next to your index.html:

webView.settings.javaScriptEnabled = true
webView.settings.domStorageEnabled = true

// connectNativeBridge() finds this interface by its name, "AndroidTour"
webView.addJavascriptInterface(object {
    @JavascriptInterface
    fun onTourEvent(json: String) {
        Log.d("Tour", json) // {"source":"tour-guide","type":"tour-step-change","index":1,...}
    }
}, "AndroidTour")

webView.loadUrl("file:///android_asset/index.html")

// Drive the tour from Kotlin, e.g. from a native "Help" button:
webView.evaluateJavascript("document.querySelector('tour-guide').start()", null)
Enter fullscreen mode Exit fullscreen mode

On a phone you get the mobile layout for free: a screen-wide card that follows the target, 44px touch targets, safe-area padding on notched devices, and repositioning when the keyboard opens.

One honest limit: custom elements need a DOM. A fully native React Native screen (<View>, not a WebView) needs a native tour library. <tour-guide> covers the web side of your app: WebView screens, React Native Web and Expo web.

Small things that save you a day

Show the tour only once

const tour = createTour({ steps });
if (!localStorage.getItem('tour-done')) tour.start();

tour.element.addEventListener('tour-end', (e) => {
  if (e.detail.reason !== 'close') localStorage.setItem('tour-done', '1');
});
Enter fullscreen mode Exit fullscreen mode

Resume where the user left off

import { enableResume } from '@xkid1/tour-guide/resume';
enableResume(tourElement, { key: 'onboarding', autoStart: true });
Enter fullscreen mode Exit fullscreen mode

Track it in your analytics

tour.element.addEventListener('tour-end', (e) =>
  analytics.track('tour_end', { reason: e.detail.reason, at: e.detail.index }),
);
Enter fullscreen mode Exit fullscreen mode

Translate it

createTour({
  steps,
  labels: {
    next: 'Siguiente',
    back: 'Atrás',
    complete: 'Listo',
    progress: (current, total) => `${current} de ${total}`,
  },
});
Enter fullscreen mode Exit fullscreen mode

How it's tested

A tour library runs inside your product, so I wanted it to be boring and dependable:

  • Strict TypeScript, with full types for steps, options and every event
  • Unit tests with coverage thresholds, and the positioning math is a pure, fully tested function
  • An end-to-end suite that packs the real npm tarball and installs it in a fresh project, then runs it in real Chromium, Firefox and WebKit, plus an Electron app
  • Gzip size budgets in CI, so the bundle can't quietly grow
  • npm releases published with provenance

Try it

npm i @xkid1/tour-guide
Enter fullscreen mode Exit fullscreen mode

It's MIT licensed and at v0.1.0, so this is the best time to shape it. If you try it, I'd love to hear what breaks, what's missing and which framework you're using. Open an issue, or leave a comment below.

If it saves you some time, a ⭐ on GitHub helps other people find it.

Top comments (0)