Skip to main content

Overview

The init() function is the primary entry point for React Grab. It initializes the library, sets up event listeners, and returns an API instance that you can use to control React Grab programmatically.

Signature

function init(options?: Options): ReactGrabAPI

Parameters

options
Options
Configuration options for React Grab

Return Value

api
ReactGrabAPI
Returns an API instance with methods to control React Grab programmatically. See ReactGrabAPI for details.

Usage

Basic Initialization

import { init } from 'react-grab';

const api = init();

With Custom Options

import { init } from 'react-grab';

const api = init({
  activationMode: 'hold',
  keyHoldDuration: 200,
  maxContextLines: 5,
  freezeReactUpdates: true
});

With Custom Activation Key

import { init } from 'react-grab';

const api = init({
  activationKey: 'KeyG', // Use 'G' key instead of 'C'
});

With Custom Content Generator

import { init } from 'react-grab';

const api = init({
  getContent: async (elements) => {
    return elements.map(el => el.outerHTML).join('\n');
  }
});

Disabling React Grab

import { init } from 'react-grab';

const api = init({ enabled: false });
// Returns a no-op API - all methods are safe to call but do nothing

Behavior

  • Single Initialization: The function can only be called once successfully. Subsequent calls return a no-op API.
  • Server-Side Rendering: When called in a non-browser environment (e.g., during SSR), returns a no-op API.
  • Built-in Plugins: Automatically registers built-in plugins (copy, comment, copyHtml, copyStyles, open).
  • Event Listeners: Sets up keyboard, mouse, and touch event listeners for element selection.
  • Cleanup: The returned API includes a dispose() method to clean up all listeners and resources.

Notes

  • The enabled option cannot be changed via setOptions() after initialization. Use setEnabled() on the API instead.
  • Options can be provided via a <script> tag with data-react-grab-options attribute, which will be merged with the options passed to init().
  • The activation key defaults to Cmd+C on Mac and Ctrl+C on Windows/Linux.

Build docs developers (and LLMs) love