Custom shape and tool

Register a custom shape and a tool that creates it, with a toolbar button and keyboard shortcut.

import { Tldraw } from 'tldraw'
import 'tldraw/tldraw.css'
import { CardShapeTool } from './CardShape/CardShapeTool'
import { CardShapeUtil } from './CardShape/CardShapeUtil'
import { components, uiOverrides } from './ui-overrides'

// There's a guide at the bottom of this file!

// [1]
const customShapeUtils = [CardShapeUtil]
const customTools = [CardShapeTool]

// [2]
export default function CustomConfigExample() {
	return (
		<div className="tldraw__editor">
			<Tldraw
				// Pass in the array of custom shape classes
				shapeUtils={customShapeUtils}
				// Pass in the array of custom tool classes
				tools={customTools}
				// Pass in any overrides to the user interface
				overrides={uiOverrides}
				components={components}
			/>
		</div>
	)
}

/*
Introduction:

This example shows how to create a custom shape, and add your own icon for it to the toolbar.
Check out CardShapeUtil.tsx and CardShapeTool.tsx to see how we define the shape util and tool.
Check out ui-overrides.tsx for more info on how to add your icon to the toolbar.

[1]
We define arrays to hold the custom shape util and custom tool. It's important to do this outside of
any React component so that the arrays don't get redefined on every render.

[2]
Now we'll pass these arrays into the Tldraw component's props, along with our ui overrides.
*/

The card shape is defined by CardShapeUtil (rendering, geometry, resizing, props validation, and migrations) and created by CardShapeTool, which extends BaseBoxShapeTool to get click-and-drag creation for free. Both are passed to <Tldraw> through the shapeUtils and tools props.

The ui-overrides.tsx file adds the tool to the UI: the tools override registers it with an icon, label, and the c shortcut, and the custom Toolbar and KeyboardShortcutsDialog components place it alongside the defaults.

Select the card tool in the toolbar (the ⚫️ icon) or press c, then click or drag on the canvas to create a card. The card's button counts clicks to show that ordinary React state works inside a shape component.

Is this page helpful?
Prev
Cubic bezier curve shape
Next
Shape with onClick