Methods in React Block Editor component
31 Aug 202524 minutes to read
The Block Editor component provides a comprehensive set of public methods to programmatically interact with and manipulate the editor content. These methods enable adding, removing, updating, and managing blocks, as well as controlling selection, formatting, and other editor operations.
Block Management Methods
Adding a block
Add a new block to the editor at a specified position using the addBlock method. This method can also insert the block before or after a target block.
// Add a new paragraph block after a specific block
const newBlock: BlockModel = {
id: 'new-block-1',
type: 'Paragraph',
content: 'This is a new paragraph block'
};
editor.addBlock(newBlock, 'target-block-id', true); // true = after, false = beforeRemoving a block
Remove a block from the editor using the removeBlock method.
// Remove a block by its ID
editor.removeBlock('block-to-remove-id');Moving a block
Move a block from one position to another within the editor using the moveBlock method.
// Move a block to a new position
editor.moveBlock('source-block-id', 'target-block-id');Updating a block
Update the properties of an existing block with the updateBlock method. Only the specified properties are modified, while others remain unchanged. It returns true if the update was successful and false otherwise.
// Update block properties
editor.updateBlock('block-id', {
isChecked: true
});Getting a block
Retrieve a block model by its unique identifier using the getBlock method. It returns null if the block is not found.
// Get a specific block
const block: BlockModel = editor.getBlock('block-id');
if (block) {
console.log('Block type:', block.type);
console.log('Block content:', block.content);
}Getting block count
Use the getBlockCount method to retrieve the total number of blocks in the editor.
// Get total block count
editor.getBlockCount();The following example demonstrates the usage of the block editor methods.
import * as React from 'react';
import * as ReactDOM from 'react-dom';
import { useEffect, useRef } from 'react';
import { BlockEditorComponent } from '@syncfusion/ej2-react-blockeditor';
import { BlockEditor, ContentType } from '@syncfusion/ej2-blockeditor';
function App() {
const editorRef = useRef(null);
useEffect(() => {
const editorInstance = editorRef.current;
// Add Block
document.getElementById('addBlockBtn').addEventListener('click', () => {
const newBlock = {
id: 'new-block',
type: 'Paragraph',
content: [
{
type: ContentType.Text,
content: 'This is a newly added block'
}
]
};
editorInstance.addBlock(newBlock, 'block-2', true);
displayOutput(`Block added successfully with ID: ${newBlock.id}`);
});
// Remove Block
document.getElementById('removeBlockBtn').addEventListener('click', () => {
editorInstance.removeBlock('block-3');
displayOutput('Block with ID "block-3" removed successfully');
});
// Get Block
document.getElementById('getBlockBtn').addEventListener('click', () => {
const block = editorInstance.getBlock('block-1');
if (block && block.content) {
displayOutput(`Block found:\nID: ${block.id}\nType: ${block.type}\nContent: ${block.content[0].content}`);
} else {
displayOutput('Block with ID "block-1" not found');
}
});
// Move Block
document.getElementById('moveBlockBtn').addEventListener('click', () => {
editorInstance.moveBlock('block-2', 'block-1');
displayOutput('Block "block-2" moved successfully');
});
// Update Block
document.getElementById('updateBlockBtn').addEventListener('click', () => {
const success = editorInstance.updateBlock('block-2', {
indent: 1,
content: [
{
content: 'Updated content'
}
]
});
const updatedBlock = editorInstance.getBlock('block-2');
if (success && updatedBlock && updatedBlock.content) {
displayOutput(`Block ${updatedBlock.id} updated successfully\nNew content: "${updatedBlock.content[0].content} \nNew indent: ${updatedBlock.indent}"`);
} else {
displayOutput('Failed to update block');
}
});
// Get Block Count
document.getElementById('getBlockCountBtn').addEventListener('click', () => {
const count = editorInstance.getBlockCount();
displayOutput(`Total number of blocks: ${count}`);
});
}, []);
const blocks = [
{
id: 'block-1',
type: 'Heading',
props: { level: 1 },
content: [{ type: ContentType.Text, content: 'Sample Heading' }]
},
{
id: 'block-2',
type: 'Paragraph',
content: [{ type: ContentType.Text, content: 'This is a sample paragraph block.' }]
},
{
id: 'block-3',
type: 'Paragraph',
content: [{ type: ContentType.Text, content: 'This is another paragraph block.' }]
}
];
function displayOutput(message) {
const outputDiv = document.getElementById('output');
if (outputDiv) {
outputDiv.textContent = message;
}
}
return (
<div>
<div id="controls">
<h3>Block Management Methods</h3>
<div class="button-group">
<button id="addBlockBtn">Add Block</button>
<button id="removeBlockBtn">Remove Block</button>
<button id="getBlockBtn">Get Block</button>
<button id="moveBlockBtn">Move Block</button>
<button id="updateBlockBtn">Update Block</button>
<button id="getBlockCountBtn">Get Block Count</button>
</div>
<div id="output"></div>
</div>
<BlockEditorComponent id="blockeditor" ref={editorRef} blocks={blocks}></BlockEditorComponent>
</div>
);
}
export default App;
ReactDOM.render(<App />, document.getElementById('container'));import * as React from 'react';
import * as ReactDOM from 'react-dom';
import { BlockEditorComponent} from '@syncfusion/ej2-react-blockeditor';
import { BlockModel, ContentType} from '@syncfusion/ej2-blockeditor';
function App() {
const editorRef = React.useRef<BlockEditorComponent>(null);
const blockData: BlockModel[] = [
{
id: 'block-1',
type: 'Heading',
props: { level: 1 },
content: [
{
type: ContentType.Text,
content: 'Sample Heading'
}
]
},
{
id: 'block-2',
type: 'Paragraph',
content: [
{
type: ContentType.Text,
content: 'This is a sample paragraph block.'
}
]
},
{
id: 'block-3',
type: 'Paragraph',
content: [
{
type: ContentType.Text,
content: 'This is another paragraph block.'
}
]
}
];
React.useEffect(() => {
const editorInstance = editorRef.current;
if (!editorInstance) return;
const addBlockBtn = document.getElementById('addBlockBtn');
const removeBlockBtn = document.getElementById('removeBlockBtn');
const getBlockBtn = document.getElementById('getBlockBtn');
const moveBlockBtn = document.getElementById('moveBlockBtn');
const updateBlockBtn = document.getElementById('updateBlockBtn');
const getBlockCountBtn = document.getElementById('getBlockCountBtn');
addBlockBtn!.addEventListener('click', () => {
const newBlock: BlockModel = {
id: 'new-block',
type: 'Paragraph',
content: [
{
type: ContentType.Text,
content: 'This is a newly added block'
}
]
};
editorInstance.addBlock(newBlock, 'block-2', true);
displayOutput(`Block added successfully with ID: ${newBlock.id}`);
});
removeBlockBtn!.addEventListener('click', () => {
editorInstance.removeBlock('block-3');
displayOutput('Block with ID "block-3" removed successfully');
});
getBlockBtn!.addEventListener('click', () => {
const block = editorInstance.getBlock('block-1');
if (block && block.content) {
displayOutput(`Block found:\nID: ${block.id}\nType: ${block.type}\nContent: ${block.content[0].content}`);
} else {
displayOutput('Block with ID "block-1" not found');
}
});
moveBlockBtn!.addEventListener('click', () => {
editorInstance.moveBlock('block-2', 'block-1');
displayOutput('Block "block-2" moved successfully');
});
updateBlockBtn!.addEventListener('click', () => {
const success = editorInstance.updateBlock('block-2', {
indent: 1,
content: [
{
type: ContentType.Text,
content: 'Updated content'
}
]
});
const updatedBlock = editorInstance.getBlock('block-2');
if (success && updatedBlock.content) {
displayOutput(`Block ${updatedBlock.id} updated successfully\nNew content: "${updatedBlock.content[0].content}"\nNew indent: ${updatedBlock.indent}`);
} else {
displayOutput('Failed to update block');
}
});
getBlockCountBtn!.addEventListener('click', () => {
const count = editorInstance.getBlockCount();
displayOutput(`Total number of blocks: ${count}`);
});
}, []);
const displayOutput = (message: string) => {
const outputDiv = document.getElementById('output');
if (outputDiv) {
outputDiv.textContent = message;
}
};
return (
<div>
<div id="controls">
<h3>Block Management Methods</h3>
<div class="button-group">
<button id="addBlockBtn">Add Block</button>
<button id="removeBlockBtn">Remove Block</button>
<button id="getBlockBtn">Get Block</button>
<button id="moveBlockBtn">Move Block</button>
<button id="updateBlockBtn">Update Block</button>
<button id="getBlockCountBtn">Get Block Count</button>
</div>
<div id="output"></div>
</div>
<BlockEditorComponent id="blockeditor" ref={editorRef} blocks={blockData}></BlockEditorComponent>
</div>
);
}
export default App;
ReactDOM.render(<App />, document.getElementById('container'));Selection and Cursor Methods
Setting text selection
Set the text selection within a specific content element using start and end positions with the setSelection method.
// Select text from position 5 to 15 in a content element
editor.setSelection('content-element-id', 5, 15);Setting cursor position
Place the cursor at a specific position within a block using the setCursorPosition method.
// Set cursor at position 10 in a block
editor.setCursorPosition('block-id', 10);Getting selected blocks
Retrieve the currently selected blocks in the editor with the getSelectedBlocks method. It returns null if no blocks are selected.
// Get all selected blocks
const selectedBlocks: BlockModel[] = editor.getSelectedBlocks();
if (selectedBlocks) {
console.log('Number of selected blocks:', selectedBlocks.length);
}Getting selection range
Get the current selection range in the editor using the getRange method. This method returns a Range object representing the selected text, or null if no selection is active.
// Get current selection range
const range: Range = editor.getRange();
if (range) {
console.log('Selection start:', range.startOffset);
console.log('Selection end:', range.endOffset);
}Setting selection range
Set the selection range in the editor using the selectRange method. This method accepts a Range object that defines the start and end positions of the selection.
// Create and select a custom range
const range: Range = document.createRange();
range.setStart(startNode, startOffset);
range.setEnd(endNode, endOffset);
editor.selectRange(range);Selecting a block
Select a specific block in the editor using the selectBlock method.
// Select a complete block
editor.selectBlock('block-id');Selecting all blocks
Select all blocks in the editor using the selectAllBlocks method.
// Select all content in the editor
editor.selectAllBlocks();The following example demonstrates the usage of the selection and cursor methods.
import * as React from 'react';
import * as ReactDOM from 'react-dom';
import { useRef, useEffect } from 'react';
import { BlockEditorComponent } from '@syncfusion/ej2-react-blockeditor';
function App() {
const blockData = [
{
id: 'heading-block',
type: 'Heading',
props: { level: 1 },
content: [
{
type: 'Text',
content: 'Welcome to Block Editor'
}
]
},
{
id: 'paragraph-1',
type: 'Paragraph',
content: [
{
id: 'paragraph1-content',
type: 'Text',
content: 'This is the first paragraph with some sample text content for selection demonstration.'
}
]
},
{
id: 'paragraph-2',
type: 'Paragraph',
content: [
{
type: 'Text',
content: 'This is the second paragraph that can be used for various selection operations.'
}
]
},
{
id: 'list-block',
type: 'BulletList',
content: [
{
type: 'Text',
content: 'First list item'
}
]
}
];
const editorRef = useRef(null);
const outputRef = useRef(null);
useEffect(() => {
const setSelectionBtn = document.getElementById('setSelectionBtn');
const setCursorBtn = document.getElementById('setCursorBtn');
const getSelectedBlocksBtn = document.getElementById('getSelectedBlocksBtn');
const getRangeBtn = document.getElementById('getRangeBtn');
const selectRangeBtn = document.getElementById('selectRangeBtn');
const selectBlockBtn = document.getElementById('selectBlockBtn');
const selectAllBtn = document.getElementById('selectAllBtn');
outputRef.current = document.getElementById('output');
const handleSetSelection = () => {
if (editorRef.current) {
editorRef.current.setSelection('paragraph1-content', 5, 15);
if (outputRef.current) {
outputRef.current.textContent = 'Text selection set in "paragraph-1" block from position 5 to 15';
}
}
};
const handleSetCursor = () => {
if (editorRef.current) {
editorRef.current.setCursorPosition('heading-block', 10);
if (outputRef.current) {
outputRef.current.textContent = 'Cursor position set at position 10 in "heading-block"';
}
}
};
const handleGetSelectedBlocks = () => {
if (editorRef.current) {
const selectedBlocks = editorRef.current.getSelectedBlocks();
if (outputRef.current) {
if (selectedBlocks && selectedBlocks.length > 0) {
const blockInfo = selectedBlocks.map(block => `ID: ${block.id}, Type: ${block.type}`).join('\n');
outputRef.current.textContent = `Selected blocks (${selectedBlocks.length}):\n${blockInfo}`;
} else {
outputRef.current.textContent = 'No blocks are currently selected';
}
}
}
};
const handleGetRange = () => {
if (editorRef.current) {
const range = editorRef.current.getRange();
if (outputRef.current) {
if (range) {
const parent = range.startContainer.nodeType === 3
? range.startContainer.parentElement
: range.startContainer;
outputRef.current.textContent = `Current selection range:
blockId: ${parent.closest('.e-block').id || 'unknown'}
Start Container: ${range.startContainer.nodeName}
Start Offset: ${range.startOffset}
End Container: ${range.endContainer.nodeName}
End Offset: ${range.endOffset}
Collapsed: ${range.collapsed}`;
} else {
outputRef.current.textContent = 'No selection range found';
}
}
}
};
const handleSelectRange = () => {
const paragraphElement = document.getElementById('paragraph-2');
if (paragraphElement) {
const range = document.createRange();
const textNode = paragraphElement.querySelector('.e-block-content').firstChild;
if (textNode && editorRef.current) {
range.setStart(textNode, 8);
range.setEnd(textNode, 20);
editorRef.current.selectRange(range);
if (outputRef.current) {
outputRef.current.textContent = 'Custom selection range applied to "paragraph-2" (positions 8-20)';
}
} else if (outputRef.current) {
outputRef.current.textContent = 'Could not find text content in paragraph-2';
}
}
};
const handleSelectBlock = () => {
if (editorRef.current) {
editorRef.current.selectBlock('heading-block');
if (outputRef.current) {
outputRef.current.textContent = 'Entire "heading-block" selected';
}
}
};
const handleSelectAll = () => {
if (editorRef.current) {
editorRef.current.selectAllBlocks();
if (outputRef.current) {
outputRef.current.textContent = 'All blocks in the editor have been selected';
}
}
};
// Attach event listeners to existing buttons
if (setSelectionBtn) {
setSelectionBtn.addEventListener('click', handleSetSelection);
}
if (setCursorBtn) {
setCursorBtn.addEventListener('click', handleSetCursor);
}
if (getSelectedBlocksBtn) {
getSelectedBlocksBtn.addEventListener('click', handleGetSelectedBlocks);
}
if (getRangeBtn) {
getRangeBtn.addEventListener('click', handleGetRange);
}
if (selectRangeBtn) {
selectRangeBtn.addEventListener('click', handleSelectRange);
}
if (selectBlockBtn) {
selectBlockBtn.addEventListener('click', handleSelectBlock);
}
if (selectAllBtn) {
selectAllBtn.addEventListener('click', handleSelectAll);
}
// Cleanup event listeners on component unmount
return () => {
if (setSelectionBtn) {
setSelectionBtn.removeEventListener('click', handleSetSelection);
}
if (setCursorBtn) {
setCursorBtn.removeEventListener('click', handleSetCursor);
}
if (getSelectedBlocksBtn) {
getSelectedBlocksBtn.removeEventListener('click', handleGetSelectedBlocks);
}
if (getRangeBtn) {
getRangeBtn.removeEventListener('click', handleGetRange);
}
if (selectRangeBtn) {
selectRangeBtn.removeEventListener('click', handleSelectRange);
}
if (selectBlockBtn) {
selectBlockBtn.removeEventListener('click', handleSelectBlock);
}
if (selectAllBtn) {
selectAllBtn.removeEventListener('click', handleSelectAll);
}
};
}, []);
return (
<div>
<div id="controls">
<h3>Selection and Cursor Methods</h3>
<div class="button-group">
<button id="setSelectionBtn">Set Text Selection</button>
<button id="setCursorBtn">Set Cursor Position</button>
<button id="getSelectedBlocksBtn">Get Selected Blocks</button>
<button id="getRangeBtn">Get Selection Range</button>
<button id="selectRangeBtn">Set Selection Range</button>
<button id="selectBlockBtn">Select Block</button>
<button id="selectAllBtn">Select All Blocks</button>
</div>
<div id="output"></div>
</div>
<BlockEditorComponent
id="blockeditor"
ref={editorRef}
blocks={blockData}></BlockEditorComponent>
</div>
);
}
export default App;
ReactDOM.render(<App />, document.getElementById('container'));import * as React from 'react';
import * as ReactDOM from 'react-dom';
import { useRef, useEffect } from 'react';
import { BlockEditorComponent, BlockModel, ContentType } from '@syncfusion/ej2-react-blockeditor';
function App() {
const blockData: BlockModel[] = [
{
id: 'heading-block',
type: 'Heading',
props: { level: 1 },
content: [
{
type: ContentType.Text,
content: 'Welcome to Block Editor'
}
]
},
{
id: 'paragraph-1',
type: 'Paragraph',
content: [
{
id: 'paragraph1-content',
type: ContentType.Text,
content: 'This is the first paragraph with some sample text content for selection demonstration.'
}
]
},
{
id: 'paragraph-2',
type: 'Paragraph',
content: [
{
type: ContentType.Text,
content: 'This is the second paragraph that can be used for various selection operations.'
}
]
},
{
id: 'list-block',
type: 'BulletList',
content: [
{
type: ContentType.Text,
content: 'First list item'
}
]
}
];
const editorRef = useRef<BlockEditorComponent | null>(null);
const outputRef = useRef<HTMLDivElement | null>(null);
useEffect(() => {
const setSelectionBtn = document.getElementById('setSelectionBtn') as HTMLElement | null;
const setCursorBtn = document.getElementById('setCursorBtn') as HTMLElement | null;
const getSelectedBlocksBtn = document.getElementById('getSelectedBlocksBtn') as HTMLElement | null;
const getRangeBtn = document.getElementById('getRangeBtn') as HTMLElement | null;
const selectRangeBtn = document.getElementById('selectRangeBtn') as HTMLElement | null;
const selectBlockBtn = document.getElementById('selectBlockBtn') as HTMLElement | null;
const selectAllBtn = document.getElementById('selectAllBtn') as HTMLElement | null;
outputRef.current = document.getElementById('output') as HTMLDivElement | null;
const handleSetSelection = () => {
if (editorRef.current) {
editorRef.current.setSelection('paragraph1-content', 5, 15);
if (outputRef.current) {
outputRef.current.textContent = 'Text selection set in "paragraph-1" block from position 5 to 15';
}
}
};
const handleSetCursor = () => {
if (editorRef.current) {
editorRef.current.setCursorPosition('heading-block', 10);
if (outputRef.current) {
outputRef.current.textContent = 'Cursor position set at position 10 in "heading-block"';
}
}
};
const handleGetSelectedBlocks = () => {
if (editorRef.current) {
const selectedBlocks = editorRef.current.getSelectedBlocks();
if (outputRef.current) {
if (selectedBlocks && selectedBlocks.length > 0) {
const blockInfo = selectedBlocks.map((block: BlockModel) => `ID: ${block.id}, Type: ${block.type}`).join('\n');
outputRef.current.textContent = `Selected blocks (${selectedBlocks.length}):\n${blockInfo}`;
} else {
outputRef.current.textContent = 'No blocks are currently selected';
}
}
}
};
const handleGetRange = () => {
if (editorRef.current) {
const range = editorRef.current.getRange();
if (outputRef.current) {
if (range) {
const parent = range.startContainer.nodeType === 3
? range.startContainer.parentElement
: range.startContainer;
outputRef.current.textContent = `Current selection range:
blockId: ${(parent as HTMLElement).closest('.e-block')!.id || 'unknown'}
Start Container: ${range.startContainer.nodeName}
Start Offset: ${range.startOffset}
End Container: ${range.endContainer.nodeName}
End Offset: ${range.endOffset}
Collapsed: ${range.collapsed}`;
} else {
outputRef.current.textContent = 'No selection range found';
}
}
}
};
const handleSelectRange = () => {
const paragraphElement = document.getElementById('paragraph-2') as HTMLElement | null;
if (paragraphElement) {
const range = document.createRange();
const textNode = paragraphElement.querySelector('.e-block-content')!.firstChild;
if (textNode && editorRef.current) {
range.setStart(textNode, 8);
range.setEnd(textNode, 20);
editorRef.current.selectRange(range);
if (outputRef.current) {
outputRef.current.textContent = 'Custom selection range applied to "paragraph-2" (positions 8-20)';
}
} else if (outputRef.current) {
outputRef.current.textContent = 'Could not find text content in paragraph-2';
}
}
};
const handleSelectBlock = () => {
if (editorRef.current) {
editorRef.current.selectBlock('heading-block');
if (outputRef.current) {
outputRef.current.textContent = 'Entire "heading-block" selected';
}
}
};
const handleSelectAll = () => {
if (editorRef.current) {
editorRef.current.selectAllBlocks();
if (outputRef.current) {
outputRef.current.textContent = 'All blocks in the editor have been selected';
}
}
};
// Attach event listeners to existing buttons
if (setSelectionBtn) {
setSelectionBtn.addEventListener('click', handleSetSelection);
}
if (setCursorBtn) {
setCursorBtn.addEventListener('click', handleSetCursor);
}
if (getSelectedBlocksBtn) {
getSelectedBlocksBtn.addEventListener('click', handleGetSelectedBlocks);
}
if (getRangeBtn) {
getRangeBtn.addEventListener('click', handleGetRange);
}
if (selectRangeBtn) {
selectRangeBtn.addEventListener('click', handleSelectRange);
}
if (selectBlockBtn) {
selectBlockBtn.addEventListener('click', handleSelectBlock);
}
if (selectAllBtn) {
selectAllBtn.addEventListener('click', handleSelectAll);
}
// Cleanup event listeners on component unmount
return () => {
if (setSelectionBtn) {
setSelectionBtn.removeEventListener('click', handleSetSelection);
}
if (setCursorBtn) {
setCursorBtn.removeEventListener('click', handleSetCursor);
}
if (getSelectedBlocksBtn) {
getSelectedBlocksBtn.removeEventListener('click', handleGetSelectedBlocks);
}
if (getRangeBtn) {
getRangeBtn.removeEventListener('click', handleGetRange);
}
if (selectRangeBtn) {
selectRangeBtn.removeEventListener('click', handleSelectRange);
}
if (selectBlockBtn) {
selectBlockBtn.removeEventListener('click', handleSelectBlock);
}
if (selectAllBtn) {
selectAllBtn.removeEventListener('click', handleSelectAll);
}
};
}, []);
return (
<div>
<div id="controls">
<h3>Selection and Cursor Methods</h3>
<div class="button-group">
<button id="setSelectionBtn">Set Text Selection</button>
<button id="setCursorBtn">Set Cursor Position</button>
<button id="getSelectedBlocksBtn">Get Selected Blocks</button>
<button id="getRangeBtn">Get Selection Range</button>
<button id="selectRangeBtn">Set Selection Range</button>
<button id="selectBlockBtn">Select Block</button>
<button id="selectAllBtn">Select All Blocks</button>
</div>
<div id="output"></div>
</div>
<BlockEditorComponent
id="blockeditor"
ref={editorRef}
blocks={blockData}></BlockEditorComponent>
</div>
);
}
export default App;
ReactDOM.render(<App />, document.getElementById('container'));Focus Management Methods
FocusIn
Use the focusIn method to programmatically set focus on the editor, making it ready for user input.
// Focus the editor
editor.focusIn();FocusOut
Use the focusOut method to programmatically remove focus from the editor. This clears any active selections and makes the editor inactive.
// Remove focus from the editor
editor.focusOut();Formatting Methods
Executing toolbar action
Execute a built-in toolbar formatting command using the executeToolbarAction method. Use this to apply formatting such as bold, italic, or color to the selected text.
// Apply bold formatting
editor.executeToolbarAction(BuiltInToolbar.Bold);
// Apply color formatting with a specific value
editor.executeToolbarAction(BuiltInToolbar.Color, '#ff0000');Enabling toolbar items
Enable specific items in the inline toolbar using the enableToolbarItems method. This method accepts a single item or an array of items to enable.
// Enable a specific toolbar item
editor.enableToolbarItems('bold');
// Work with multiple items
editor.enableToolbarItems(['bold', 'italic', 'underline']);Disabling toolbar items
Disable specific items in the inline toolbar using the disableToolbarItems method. This method accepts a single item or an array of items to disable.
// Disable a specific toolbar items
editor.disableToolbarItems('bold');
// Disable multiple items
editor.disableToolbarItems(['bold', 'italic', 'underline']);The following example demonstrates the usage of the formatting and focus methods.
import * as React from 'react';
import * as ReactDOM from 'react-dom';
import { useRef, useState, useEffect } from 'react';
import { BlockEditorComponent } from '@syncfusion/ej2-react-blockeditor';
function App() {
const blocksData = [
{
id: 'sample-heading',
type: 'Heading',
props: { level: 1 },
content: [
{
type: 'Text',
content: 'Formatting Demo'
}
]
},
{
id: 'sample-paragraph-1',
type: 'Paragraph',
content: [
{
type: 'Text',
content: 'Select this text and apply different formatting options using the buttons below. You can make text bold or change colors for the text.'
}
]
},
{
id: 'sample-list',
type: 'BulletList',
content: [
{
type: 'Text',
content: 'List item for formatting demonstration'
}
]
}
];
const blockEditorRef = useRef(null);
const [outputMessage, setOutputMessage] = useState('');
useEffect(() => {
const applyBoldBtn = document.getElementById('applyBoldBtn');
const applyColorBtn = document.getElementById('applyColorBtn');
const enableToolbarBtn = document.getElementById('enableToolbarBtn');
const disableToolbarBtn = document.getElementById('disableToolbarBtn');
const outputDiv = document.getElementById('output');
const handleApplyBold = () => {
if (blockEditorRef.current) {
blockEditorRef.current.executeToolbarAction('Bold');
setOutputMessage('Bold formatting applied to selected text');
}
};
const handleApplyColor = () => {
if (blockEditorRef.current) {
blockEditorRef.current.executeToolbarAction('Color', '#ff6b35');
setOutputMessage('Orange color (#ff6b35) applied to selected text');
}
};
const handleEnableToolbar = () => {
if (blockEditorRef.current) {
blockEditorRef.current.enableToolbarItems(['bold', 'italic', 'underline']);
setOutputMessage('Toolbar items (bold, italic, underline) have been enabled');
}
};
const handleDisableToolbar = () => {
if (blockEditorRef.current) {
blockEditorRef.current.disableToolbarItems(['bold', 'italic']);
setOutputMessage('Toolbar items (bold, italic) have been disabled');
}
};
// Attach event listeners to existing buttons
if (applyBoldBtn) {
applyBoldBtn.addEventListener('click', handleApplyBold);
}
if (applyColorBtn) {
applyColorBtn.addEventListener('click', handleApplyColor);
}
if (enableToolbarBtn) {
enableToolbarBtn.addEventListener('click', handleEnableToolbar);
}
if (disableToolbarBtn) {
disableToolbarBtn.addEventListener('click', handleDisableToolbar);
}
// Update output div when outputMessage changes
if (outputDiv) {
outputDiv.textContent = outputMessage;
}
// Cleanup event listeners on component unmount
return () => {
if (applyBoldBtn) {
applyBoldBtn.removeEventListener('click', handleApplyBold);
}
if (applyColorBtn) {
applyColorBtn.removeEventListener('click', handleApplyColor);
}
if (enableToolbarBtn) {
enableToolbarBtn.removeEventListener('click', handleEnableToolbar);
}
if (disableToolbarBtn) {
disableToolbarBtn.removeEventListener('click', handleDisableToolbar);
}
};
}, [outputMessage]);
return (
<div>
<div id="controls">
<h3>Formatting Methods</h3>
<div class="button-group">
<button id="applyBoldBtn">Apply Bold </button>
<button id="applyColorBtn">Apply Color</button>
<button id="enableToolbarBtn">Enable Toolbar Items</button>
<button id="disableToolbarBtn">Disable Toolbar Items</button>
</div>
<div class="instruction">
<p><strong>Instructions:</strong> Select some text in the editor first, then click the formatting buttons to see the effects.</p>
</div>
<div id="output"></div>
</div>
<BlockEditorComponent
id="blockeditor"
ref={blockEditorRef}
blocks={blocksData}></BlockEditorComponent>
</div>
);
}
export default App;
ReactDOM.render(<App />, document.getElementById('container'));import * as React from 'react';
import * as ReactDOM from 'react-dom';
import { useRef, useState, useEffect } from 'react';
import { BlockEditorComponent, BlockModel, ContentType } from '@syncfusion/ej2-react-blockeditor';
function App() {
const blocksData: BlockModel[] = [
{
id: 'sample-heading',
type: 'Heading',
props: { level: 1 },
content: [
{
type: ContentType.Text,
content: 'Formatting Demo'
}
]
},
{
id: 'sample-paragraph-1',
type: 'Paragraph',
content: [
{
type: ContentType.Text,
content: 'Select this text and apply different formatting options using the buttons below. You can make text bold or change colors for the text.'
}
]
},
{
id: 'sample-list',
type: 'BulletList',
content: [
{
type: ContentType.Text,
content: 'List item for formatting demonstration'
}
]
}
];
const blockEditorRef = useRef<BlockEditorComponent | null>(null);
const [outputMessage, setOutputMessage] = useState<string>('');
useEffect(() => {
const applyBoldBtn = document.getElementById('applyBoldBtn');
const applyColorBtn = document.getElementById('applyColorBtn');
const enableToolbarBtn = document.getElementById('enableToolbarBtn');
const disableToolbarBtn = document.getElementById('disableToolbarBtn');
const outputDiv = document.getElementById('output');
const handleApplyBold = () => {
if (blockEditorRef.current) {
blockEditorRef.current.executeToolbarAction('Bold');
setOutputMessage('Bold formatting applied to selected text');
}
};
const handleApplyColor = () => {
if (blockEditorRef.current) {
blockEditorRef.current.executeToolbarAction('Color', '#ff6b35');
setOutputMessage('Orange color (#ff6b35) applied to selected text');
}
};
const handleEnableToolbar = () => {
if (blockEditorRef.current) {
blockEditorRef.current.enableToolbarItems(['bold', 'italic', 'underline']);
setOutputMessage('Toolbar items (bold, italic, underline) have been enabled');
}
};
const handleDisableToolbar = () => {
if (blockEditorRef.current) {
blockEditorRef.current.disableToolbarItems(['bold', 'italic']);
setOutputMessage('Toolbar items (bold, italic) have been disabled');
}
};
// Attach event listeners to existing buttons
if (applyBoldBtn) {
applyBoldBtn.addEventListener('click', handleApplyBold);
}
if (applyColorBtn) {
applyColorBtn.addEventListener('click', handleApplyColor);
}
if (enableToolbarBtn) {
enableToolbarBtn.addEventListener('click', handleEnableToolbar);
}
if (disableToolbarBtn) {
disableToolbarBtn.addEventListener('click', handleDisableToolbar);
}
// Update output div when outputMessage changes
if (outputDiv) {
outputDiv.textContent = outputMessage;
}
// Cleanup event listeners on component unmount
return () => {
if (applyBoldBtn) {
applyBoldBtn.removeEventListener('click', handleApplyBold);
}
if (applyColorBtn) {
applyColorBtn.removeEventListener('click', handleApplyColor);
}
if (enableToolbarBtn) {
enableToolbarBtn.removeEventListener('click', handleEnableToolbar);
}
if (disableToolbarBtn) {
disableToolbarBtn.removeEventListener('click', handleDisableToolbar);
}
};
}, [outputMessage]);
return (
<div>
<div id="controls">
<h3>Formatting Methods</h3>
<div class="button-group">
<button id="applyBoldBtn">Apply Bold </button>
<button id="applyColorBtn">Apply Color</button>
<button id="enableToolbarBtn">Enable Toolbar Items</button>
<button id="disableToolbarBtn">Disable Toolbar Items</button>
</div>
<div class="instruction">
<p><strong>Instructions:</strong> Select some text in the editor first, then click the formatting buttons to see the effects.</p>
</div>
<div id="output"></div>
</div>
<BlockEditorComponent
id="blockeditor"
ref={blockEditorRef}
blocks={blocksData}></BlockEditorComponent>
</div>
);
}
export default App;
ReactDOM.render(<App />, document.getElementById('container'));Data Export Methods
Getting data as JSON
Export the editor content in JSON format using the getDataAsJson method. This method allows exporting all blocks or a specific block.
// Get all blocks as JSON
const allBlocks = editor.getDataAsJson();
// Get a specific block as JSON
const specificBlock = editor.getDataAsJson('block-id');Getting data as HTML
Export the editor content in HTML format using the getDataAsHtml method. This method allows exporting all blocks or a specific block.
// Get all blocks as HTML
const allBlocksHtml: string = editor.getDataAsHtml();
// Get a specific block as HTML
const specificBlockHtml: string = editor.getDataAsHtml('block-id');Printing editor content
Print the editor content using the print method. This action opens the browser’s print dialog with the current editor content.
// Print the editor content
editor.print();The following example demonstrates the usage of the data export methods.
import * as React from 'react';
import * as ReactDOM from 'react-dom';
import { useRef, useEffect } from 'react';
import { BlockEditorComponent } from '@syncfusion/ej2-react-blockeditor';
function App() {
const blockData = [
{
id: 'title-block',
type: 'Heading',
props: { level: 1 },
content: [{ type: 'Text', content: 'Document Export Demo' }]
},
{
id: 'intro-paragraph',
type: 'Paragraph',
content: [
{
type: 'Text',
content:
'This document demonstrates the data export capabilities of the Block Editor. You can export content as JSON or HTML formats.'
}
]
},
{
id: 'features-heading',
type: 'Heading',
props: { level: 2},
content: [{ type: 'Text', content: 'Export Features' }]
},
{
id: 'features-list',
type: 'BulletList',
content: [{ type: 'Text', content: 'JSON export for data processing' }]
},
{
id: 'features-list-2',
type: 'BulletList',
content: [{ type: 'Text', content: 'HTML export for web display' }]
},
{
id: 'features-list-3',
type: 'BulletList',
content: [{ type: 'Text', content: 'Print functionality for hard copies' }]
},
{
id: 'code-example',
type: 'Code',
content: [
{
type: 'Text',
content: 'var data = editor.getDataAsJson();\nconsole.log(data);'
}
]
}
];
const editorRef = useRef(null);
const outputRef = useRef(null);
useEffect(() => {
const getJsonAllBtn = document.getElementById('getJsonAllBtn');
const getJsonBlockBtn = document.getElementById('getJsonBlockBtn');
const getHtmlAllBtn = document.getElementById('getHtmlAllBtn');
const getHtmlBlockBtn = document.getElementById('getHtmlBlockBtn');
const printContentBtn = document.getElementById('printContentBtn');
outputRef.current = document.getElementById('output');
const handleGetJsonAll = () => {
if (editorRef.current) {
const jsonData = editorRef.current.getDataAsJson();
const formattedJson = JSON.stringify(jsonData, null, 2);
if (outputRef.current) {
outputRef.current.textContent = `All blocks as JSON:\n\n${formattedJson}`;
}
}
};
const handleGetJsonBlock = () => {
if (editorRef.current) {
const blockData = editorRef.current.getDataAsJson('title-block');
const formattedJson = JSON.stringify(blockData, null, 2);
if (outputRef.current) {
outputRef.current.textContent = `Block "title-block" as JSON:\n\n${formattedJson}`;
}
}
};
const handleGetHtmlAll = () => {
if (editorRef.current) {
const htmlData = editorRef.current.getDataAsHtml();
if (outputRef.current) {
outputRef.current.textContent = `All blocks as HTML:\n\n${htmlData}`;
}
}
};
const handleGetHtmlBlock = () => {
if (editorRef.current) {
const blockHtml = editorRef.current.getDataAsHtml('intro-paragraph');
if (outputRef.current) {
outputRef.current.textContent = `Block "intro-paragraph" as HTML:\n\n${blockHtml}`;
}
}
};
const handlePrintContent = () => {
if (editorRef.current) {
editorRef.current.print();
if (outputRef.current) {
outputRef.current.textContent = 'Print dialog opened. Check for a new browser window/tab with the printable content.';
}
}
};
// Attach event listeners to existing buttons
if (getJsonAllBtn) {
getJsonAllBtn.addEventListener('click', handleGetJsonAll);
}
if (getJsonBlockBtn) {
getJsonBlockBtn.addEventListener('click', handleGetJsonBlock);
}
if (getHtmlAllBtn) {
getHtmlAllBtn.addEventListener('click', handleGetHtmlAll);
}
if (getHtmlBlockBtn) {
getHtmlBlockBtn.addEventListener('click', handleGetHtmlBlock);
}
if (printContentBtn) {
printContentBtn.addEventListener('click', handlePrintContent);
}
// Cleanup event listeners on component unmount
return () => {
if (getJsonAllBtn) {
getJsonAllBtn.removeEventListener('click', handleGetJsonAll);
}
if (getJsonBlockBtn) {
getJsonBlockBtn.removeEventListener('click', handleGetJsonBlock);
}
if (getHtmlAllBtn) {
getHtmlAllBtn.removeEventListener('click', handleGetHtmlAll);
}
if (getHtmlBlockBtn) {
getHtmlBlockBtn.removeEventListener('click', handleGetHtmlBlock);
}
if (printContentBtn) {
printContentBtn.removeEventListener('click', handlePrintContent);
}
};
}, []);
return (
<div>
<div id="controls">
<h3>Data Export Methods</h3>
<div class="button-group">
<button id="getJsonAllBtn">Get All Data as JSON</button>
<button id="getJsonBlockBtn">Get Block Data as JSON</button>
<button id="getHtmlAllBtn">Get All Data as HTML</button>
<button id="getHtmlBlockBtn">Get Block Data as HTML</button>
<button id="printContentBtn">Print Editor Content</button>
</div>
<div id="output"></div>
</div>
<BlockEditorComponent
id="blockeditor"
ref={editorRef}
blocks={blockData}></BlockEditorComponent>
</div>
);
}
export default App;
ReactDOM.render(<App />, document.getElementById('container'));import * as React from 'react';
import * as ReactDOM from 'react-dom';
import { useRef, useEffect } from 'react';
import { BlockEditorComponent, BlockModel, ContentType } from '@syncfusion/ej2-react-blockeditor';
function App() {
const blockData: BlockModel[] = [
{
id: 'title-block',
type: 'Heading',
props: { level: 1 },
content: [{ type: ContentType.Text, content: 'Document Export Demo' }]
},
{
id: 'intro-paragraph',
type: 'Paragraph',
content: [
{
type: ContentType.Text,
content:
'This document demonstrates the data export capabilities of the Block Editor. You can export content as JSON or HTML formats.'
}
]
},
{
id: 'features-heading',
type: 'Heading',
props: { level: 2},
content: [{ type: ContentType.Text, content: 'Export Features' }]
},
{
id: 'features-list',
type: 'BulletList',
content: [{ type: ContentType.Text, content: 'JSON export for data processing' }]
},
{
id: 'features-list-2',
type: 'BulletList',
content: [{ type: ContentType.Text, content: 'HTML export for web display' }]
},
{
id: 'features-list-3',
type: 'BulletList',
content: [{ type: ContentType.Text, content: 'Print functionality for hard copies' }]
},
{
id: 'code-example',
type: 'Code',
content: [
{
type: ContentType.Text,
content: 'var data = editor.getDataAsJson();\nconsole.log(data);'
}
]
}
];
const editorRef = useRef<BlockEditorComponent | null>(null);
const outputRef = useRef<HTMLDivElement | null>(null);
useEffect(() => {
const getJsonAllBtn = document.getElementById('getJsonAllBtn') as HTMLElement | null;
const getJsonBlockBtn = document.getElementById('getJsonBlockBtn') as HTMLElement | null;
const getHtmlAllBtn = document.getElementById('getHtmlAllBtn') as HTMLElement | null;
const getHtmlBlockBtn = document.getElementById('getHtmlBlockBtn') as HTMLElement | null;
const printContentBtn = document.getElementById('printContentBtn') as HTMLElement | null;
outputRef.current = document.getElementById('output') as HTMLDivElement | null;
const handleGetJsonAll = () => {
if (editorRef.current) {
const jsonData = editorRef.current.getDataAsJson();
const formattedJson = JSON.stringify(jsonData, null, 2);
if (outputRef.current) {
outputRef.current.textContent = `All blocks as JSON:\n\n${formattedJson}`;
}
}
};
const handleGetJsonBlock = () => {
if (editorRef.current) {
const blockData = editorRef.current.getDataAsJson('title-block');
const formattedJson = JSON.stringify(blockData, null, 2);
if (outputRef.current) {
outputRef.current.textContent = `Block "title-block" as JSON:\n\n${formattedJson}`;
}
}
};
const handleGetHtmlAll = () => {
if (editorRef.current) {
const htmlData = editorRef.current.getDataAsHtml();
if (outputRef.current) {
outputRef.current.textContent = `All blocks as HTML:\n\n${htmlData}`;
}
}
};
const handleGetHtmlBlock = () => {
if (editorRef.current) {
const blockHtml = editorRef.current.getDataAsHtml('intro-paragraph');
if (outputRef.current) {
outputRef.current.textContent = `Block "intro-paragraph" as HTML:\n\n${blockHtml}`;
}
}
};
const handlePrintContent = () => {
if (editorRef.current) {
editorRef.current.print();
if (outputRef.current) {
outputRef.current.textContent = 'Print dialog opened. Check for a new browser window/tab with the printable content.';
}
}
};
// Attach event listeners to existing buttons
if (getJsonAllBtn) {
getJsonAllBtn.addEventListener('click', handleGetJsonAll);
}
if (getJsonBlockBtn) {
getJsonBlockBtn.addEventListener('click', handleGetJsonBlock);
}
if (getHtmlAllBtn) {
getHtmlAllBtn.addEventListener('click', handleGetHtmlAll);
}
if (getHtmlBlockBtn) {
getHtmlBlockBtn.addEventListener('click', handleGetHtmlBlock);
}
if (printContentBtn) {
printContentBtn.addEventListener('click', handlePrintContent);
}
// Cleanup event listeners on component unmount
return () => {
if (getJsonAllBtn) {
getJsonAllBtn.removeEventListener('click', handleGetJsonAll);
}
if (getJsonBlockBtn) {
getJsonBlockBtn.removeEventListener('click', handleGetJsonBlock);
}
if (getHtmlAllBtn) {
getHtmlAllBtn.removeEventListener('click', handleGetHtmlAll);
}
if (getHtmlBlockBtn) {
getHtmlBlockBtn.removeEventListener('click', handleGetHtmlBlock);
}
if (printContentBtn) {
printContentBtn.removeEventListener('click', handlePrintContent);
}
};
}, []);
return (
<div>
<div id="controls">
<h3>Data Export Methods</h3>
<div class="button-group">
<button id="getJsonAllBtn">Get All Data as JSON</button>
<button id="getJsonBlockBtn">Get Block Data as JSON</button>
<button id="getHtmlAllBtn">Get All Data as HTML</button>
<button id="getHtmlBlockBtn">Get Block Data as HTML</button>
<button id="printContentBtn">Print Editor Content</button>
</div>
<div id="output"></div>
</div>
<BlockEditorComponent
id="blockeditor"
ref={editorRef}
blocks={blockData}></BlockEditorComponent>
</div>
);
}
export default App;
ReactDOM.render(<App />, document.getElementById('container'));