Richtext replacement

Replace selected rich text elements with formatted content.

Running this example

To run this example locally:

  1. If you haven't already, create a new app in the Developer Portal(opens in a new tab or window). For more information, refer to our Quickstart guide.

  2. In your app's configuration on the Developer Portal(opens in a new tab or window), ensure the "Development URL" is set to http://localhost:8080.

  3. Clone the starter kit:

    git clone https://github.com/canva-sdks/canva-apps-sdk-starter-kit.git
    cd canva-apps-sdk-starter-kit
    SHELL
  4. Install dependencies:

    npm install
    SHELL
  5. Run the example:

    npm run start richtext_replacement
    SHELL
  6. Click the Preview URL link shown in the terminal to open the example in the Canva editor.

Example app source code

// For usage information, see the README.md file.
import { Button, Rows, Text } from "@canva/app-ui-kit";
import { useEffect, useState } from "react";
import type { SelectionEvent } from "@canva/design";
import { selection } from "@canva/design";
import * as styles from "styles/components.css";
export const App = () => {
// State to track the current selection of richtext elements
const [selectionState, setSelectionState] = useState<
SelectionEvent<"richtext">
>({
count: 0,
scope: "richtext",
read: () =>
Promise.resolve({
contents: [],
save: () => Promise.resolve(),
}),
});
// Register for selection changes to enable text manipulation when text is selected
useEffect(() => {
selection.registerOnChange({
scope: "richtext",
onChange: (evt) => {
if (evt.count > 0) {
setSelectionState(evt);
}
},
});
}, []);
// Toggles bold formatting for the selected richtext by reading current formatting
// and applying the opposite state
const updateFormatting = async () => {
if (!selectionState) {
return;
}
// Create a draft to make changes to the selected richtext
const draft = await selectionState.read();
for (const richtext of draft.contents) {
// Read text regions to access formatting information
const regions = await richtext.readTextRegions();
let index = 0;
regions.forEach((region) => {
// Toggle bold state: if currently bold, make normal; if normal, make bold
richtext.formatText(
{ index, length: region.text.length },
{
fontWeight:
region.formatting?.fontWeight === "bold" ? "normal" : "bold",
},
);
index = index + region.text.length;
});
}
// Save changes to apply them to the design
await draft.save();
};
// Appends an exclamation mark to the end of selected richtext elements
const appendText = async () => {
if (!selectionState) {
return;
}
const draft = await selectionState.read();
// Append text to each selected richtext element
draft.contents.forEach((richtext) => richtext.appendText("!"));
await draft.save();
};
// Replaces all selected richtext content with underlined "Hello World"
const replaceText = async () => {
if (!selectionState) {
return;
}
const draft = await selectionState.read();
for (const richtext of draft.contents) {
// Get the current text length to replace the entire content
const plaintext = await richtext.readPlaintext();
// Replace all text with "Hello World" and apply underline formatting
richtext.replaceText(
{ index: 0, length: plaintext.length },
"Hello World",
{ decoration: "underline" },
);
}
await draft.save();
};
return (
<div className={styles.scrollContainer}>
<Rows spacing="2u">
<Text>
This example demonstrates how apps can replace the selected text.
Select a text in the editor to begin.
</Text>
<Button
variant="primary"
onClick={updateFormatting}
disabled={selectionState.count === 0}
>
Toggle bold
</Button>
<Button
variant="primary"
onClick={appendText}
disabled={selectionState.count === 0}
>
Append "!"
</Button>
<Button
variant="primary"
onClick={replaceText}
disabled={selectionState.count === 0}
>
Replace with underlined "Hello World"
</Button>
</Rows>
</div>
);
};
TYPESCRIPT
// For usage information, see the README.md file.
import { createRoot } from "react-dom/client";
import { App } from "./app";
import "@canva/app-ui-kit/styles.css";
import { AppUiProvider } from "@canva/app-ui-kit";
const root = createRoot(document.getElementById("root") as Element);
function render() {
root.render(
<AppUiProvider>
<App />
</AppUiProvider>,
);
}
render();
// Hot Module Replacement for development (automatically reloads the app when changes are made)
if (module.hot) {
module.hot.accept("./app", render);
}
TYPESCRIPT
# Rich text replacement
Demonstrates how to replace and modify selected rich text elements including formatting changes like bold, italics, and other text properties. Shows advanced text selection and formatting manipulation.
For API reference docs and instructions on running this example, see: https://www.canva.dev/docs/apps/examples/richtext-replacement/.
Related examples: See content_replacement/text_replacement for plain text substitution, or design_elements/richtext_elements for rich text insertion.
NOTE: This example differs from what is expected for public apps to pass a Canva review:
- Text content and formatting operations are hardcoded for demonstration purposes only. Production apps should provide user input interfaces or dynamic content loading and comprehensive text editing capabilities
- Text formatting handling is simplified for demonstration. Production apps should handle complex formatting scenarios and preserve user styling where appropriate
- Error handling is simplified for demonstration. Production apps must implement comprehensive error handling with clear user feedback and graceful failure modes
- Internationalization is not implemented. Production apps must support multiple languages using the `@canva/app-i18n-kit` package to pass Canva review requirements
MARKDOWN

API reference

Need help?