Before delete shape
Intercept shape deletions and cancel the ones you don't want to allow.
import { Editor, Tldraw, createShapeId, toRichText } from 'tldraw'
import 'tldraw/tldraw.css'
export default function BeforeDeleteShapeExample() {
return (
<div className="tldraw__editor">
<Tldraw
onMount={(editor) => {
editor.sideEffects.registerBeforeDeleteHandler('shape', (shape) => {
if ('color' in shape.props && shape.props.color === 'red') {
return false
}
return
})
createDemoShapes(editor)
}}
/>
</div>
)
}
function createDemoShapes(editor: Editor) {
editor
.createShapes([
{
id: createShapeId(),
type: 'text',
props: {
richText: toRichText("Red shapes can't be deleted"),
color: 'red',
},
},
{
id: createShapeId(),
type: 'text',
y: 30,
props: {
richText: toRichText('but other shapes can'),
color: 'black',
},
},
])
.zoomToFit({ animation: { duration: 0 } })
}
editor.sideEffects.registerBeforeDeleteHandler runs before a record is removed from the store.
Return false to cancel the deletion; return nothing to let it proceed. In this example, red shapes
can't be deleted but everything else can.
Try selecting each text shape and pressing delete. The red one stays put, whether you delete it directly, select all and delete, or cut it. This only guards deletions: the user can still recolor the shape and then delete it.
Is this page helpful?
Prev
Before create/update shapeNext
Custom double-click behavior