Shape with onClick

Handle clicks on a custom shape with ShapeUtil.onClick.

import { Tldraw } from 'tldraw'
import 'tldraw/tldraw.css'
import { ClickableShapeUtil } from './ClickableShapeUtil'

// [1]
const customShapeUtils = [ClickableShapeUtil]

// [2]
export default function ShapeWithOnClickExample() {
	return (
		<div className="tldraw__editor">
			<Tldraw
				shapeUtils={customShapeUtils}
				onMount={(editor) => {
					editor.createShape({
						type: 'clickable',
						x: 200,
						y: 200,
					})
				}}
			/>
		</div>
	)
}

/*
[1]
We define the custom shape utils array outside of the component so it doesn't get recreated
on every render.

[2]
We pass our custom shape util to the Tldraw component and create an initial shape on mount
so there's something to interact with right away.

Try it:
- Click the shape to increment the counter
- Drag the shape to move it
- Both work whether or not the shape is selected
*/

Implement onClick on your shape util to react when the user clicks the shape. The select tool calls it on pointer up when the pointer didn't drag; return a shape partial and the editor applies it (and skips selecting the shape), or return nothing to fall through to normal selection.

Unlike a React onClick on a DOM element inside the shape component, ShapeUtil.onClick goes through the editor's event system, so clicking and dragging both work on selected and unselected shapes. Try clicking the shape to bump the counter, then dragging it.

Is this page helpful?
Prev
Custom shape and tool
Next
Shape with onDoubleClickEdge