Skip to content

HotkeysTarget & useHotkeys migration

Adi Dahiya edited this page May 3, 2023 · 5 revisions

HotkeysTarget in Blueprint v6.0 features some breaking changes. To help you migrate, @blueprintjs/core provides a component called HotkeysTarget2 in v3.39.0+. Alternatively, you can switch to using the useHotkeys hook directly, which HotkeysTarget2 uses under the hood.

HotkeysTarget / useHotkeys Requirements

  • useHotkeys is a custom React hook, so you must use React 16.8+, otherwise it will fail at runtime. @blueprintjs/core >=v3.39.0 <4.0.0 is lenient about its React peer dependency and will not enforce this constraint for you.
  • You must configure HotkeysProvider near the root of your React component tree:
import { HotkeysProvider } from "@blueprintjs/core";
import React from "react";
import ReactDOM from "react-dom";

ReactDOM.render(
  <HotkeysProvider>
    // your app
  </HotkeysProvider>,
  ...
);

Notable changes compared to HotkeysTarget

The hotkeys API has been overhauled to use modern React APIs. It now works with function components and no longer requires your build system to support decorators.

import { useHotkeys } from "@blueprintjs/core";
import React from "react";

export default function HotkeysExample() {
    const { handleKeyDown, handleKeyUp } = useHotkeys([
        // define hotkeys
    ]);

    return (
        <div className="my-hotkeys-example" onKeyDown={handleKeyDown} onKeyUp={handleKeyUp}>
            try me
        </div>
    );
}

Alternatively, use HotkeysTarget2 inside a class component:

import { HotkeyConfig, HotkeysTarget2 } from "@blueprintjs/core";
import React from "react";

export default class extends React.Component {
    private hotkeys: HotkeyConfig[] = [
        // define hotkeys
    ];

    public render() {
        return (
            <HotkeysTarget2 hotkeys={this.hotkeys}>
                {({ handleKeyDown, handleKeyUp }) => (
                    <div className="my-hotkeys-example" onKeyDown={handleKeyDown} onKeyUp={handleKeyUp}>
                        try me
                    </div>
                )}
            </HotkeysTarget2>
        );
    }
}

Important for @blueprintjs/table users

The new hotkeys API renders its help dialog (shown by pressing the ? key) differently from the old @HotkeysTarget API. As such, you may find yourself with multiple hotkeys dialogs rendered if you mix the old and new APIs (#4789 has more details on this issue). If you use @blueprintjs/table, you may be using the old hotkeys dialog API indirectly when you render a <Table>. So, to fully migrate to the new hotkeys API, you must:

  • upgrade to @blueprintjs/table v3.9.0+
  • migrate from <Table> to <Table2> (see docs)
  • migrate from <EditableCell> to <EditableCell2> (no API changes)
Clone this wiki locally