apps/docs/content/docs/editor.mdx
The Editor class is the main way of controlling tldraw's editor. You can use it to manage the editor's internal state, make changes to the document, or respond to changes that have occurred.
By design, the Editor's surface area is very large. Almost everything is available through it. Need to create some shapes? Use Editor#createShapes. Need to delete them? Use Editor#deleteShapes. Need a sorted array of every shape on the current page? Use Editor#getCurrentPageShapesSorted.
You can access the editor in two ways:
The Tldraw component's onMount callback provides the editor as the first argument.
function App() {
return (
<Tldraw
onMount={(editor) => {
// your editor code here
}}
/>
)
}
The useEditor hook returns the editor instance. It must be called from within the JSX of the Tldraw component.
function InsideOfContext() {
const editor = useEditor()
// your editor code here
return null
}
function App() {
return (
<Tldraw>
<InsideOfContext />
</Tldraw>
)
}
If you're using the subcomponents as shown in this example, the editor instance is provided by the TldrawEditor component.
The editor's state is reactive. Methods like Editor#getSelectedShapeIds or Editor#getCurrentPageShapes return values that automatically update when the underlying data changes. You can use these values directly in React components with the track wrapper or useValue hook.
import { track, useEditor } from 'tldraw'
export const SelectedShapeIdsCount = track(() => {
const editor = useEditor()
return <div>{editor.getSelectedShapeIds().length}</div>
})
See the Signals article for more on tldraw's reactive state system.
Each change to the editor happens within a transaction. You can batch multiple changes into a single transaction using the Editor#run method. Batching improves performance and reduces overhead for persisting or distributing changes.
editor.run(() => {
editor.createShapes(myShapes)
editor.sendToBack(myShapes)
editor.selectNone()
})
The run method also accepts options to control history and locked shape behavior:
// Make changes without affecting undo/redo history
editor.run(
() => {
editor.createShapes(myShapes)
},
{ history: 'ignore' }
)
// Make changes to locked shapes
editor.run(
() => {
editor.updateShapes(myLockedShapes)
},
{ ignoreShapeLock: true }
)
The editor provides methods and properties organized around these areas:
See the Editor API reference for the complete list of methods and properties.