Examples
App elements
Assets and media
Fundamentals
Intents
Design interaction
Drag and drop
Design elements
Localization
Content replacement
Fonts
Use the fonts picker to apply custom fonts to text elements in designs.
Running this example
To run this example locally:
-
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.
-
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
. -
Clone the starter kit:
git clone https://github.com/canva-sdks/canva-apps-sdk-starter-kit.gitcd canva-apps-sdk-starter-kitSHELL -
Install dependencies:
npm installSHELL -
Run the example:
npm run start fontsSHELL -
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 {Box,Button,ChevronDownIcon,FormField,Rows,Select,Text,TextInput,Title,SegmentedControl,ImageCard,} from "@canva/app-ui-kit";import type { Font, FontStyle, FontWeightName } from "@canva/asset";// Canva's Font APIs for discovering available fonts and opening the font pickerimport { findFonts, requestFontSelection } from "@canva/asset";import { useState, useEffect, useCallback } from "react";import * as styles from "styles/components.css";import { useAddElement } from "utils/use_add_element";type TextConfig = {text: string;color: string;fontWeight: FontWeightName;fontStyle: FontStyle;};const initialConfig: TextConfig = {text: "Hello world",color: "#8B3DFF",fontWeight: "normal",fontStyle: "normal",};const fontStyleOptions: {value: FontStyle;label: FontStyle;disabled?: boolean;}[] = [{ value: "normal", label: "normal", disabled: false },{ value: "italic", label: "italic", disabled: false },];export const App = () => {const addElement = useAddElement();const [textConfig, setTextConfig] = useState<TextConfig>(initialConfig);const [selectedFont, setSelectedFont] = useState<Font | undefined>(undefined);const [availableFonts, setAvailableFonts] = useState<readonly Font[]>([]);// Fetch all fonts available in Canva using the findFonts APIconst fetchFonts = useCallback(async () => {const response = await findFonts();setAvailableFonts(response.fonts);}, [setAvailableFonts]);useEffect(() => {fetchFonts();}, [fetchFonts]);const { text, fontWeight, fontStyle } = textConfig;const disabled = text.trim().length === 0;const availableFontWeights = getFontWeights(selectedFont);const availableFontStyles = getFontStyles(fontWeight, selectedFont);const availableStyleValues = new Set(availableFontStyles.map((style) => style.value),); // Create a Set for lookupconst availableFontStyleOptions = fontStyleOptions.map((styleOption) => {// Check if the current style option is NOT present in the available styles.if (!availableStyleValues.has(styleOption.value)) {// If so, return a new object with `disabled` set to true, keeping the rest of the object the same.return { ...styleOption, disabled: true };}// If the style is available, return it as is. Also ensures disabled is set to false explicitly if not already defined.return { ...styleOption, disabled: false };});const resetSelectedFontStyleAndWeight = (selectedFont?: Font) => {setTextConfig((prevState) => {return {...prevState,fontStyle:getFontStyles(fontWeight, selectedFont)[0]?.value || "normal",fontWeight: getFontWeights(selectedFont)[0]?.value || "normal",};});};return (<div className={styles.scrollContainer}><Rows spacing="2u"><Text>This example demonstrates how apps can apply fonts to text elementsand add to design.</Text><FormFieldlabel="Text"value={text}control={(props) => (<TextInput{...props}onChange={(value) => {setTextConfig((prevState) => {return {...prevState,text: value,};});}}/>)}/><Title size="small">Font selection</Title>{availableFonts.length > 0 && (<FormFieldlabel="Font family"value={selectedFont?.ref}control={(props) => (<Select{...props}stretchonChange={(ref) => {const selected = availableFonts.find((f) => f.ref === ref);setSelectedFont(selected);resetSelectedFontStyleAndWeight(selected);}}options={availableFonts.map((f) => ({value: f.ref,label: f.name,}))}/>)}/>)}<Buttonvariant="secondary"icon={ChevronDownIcon}iconPosition="end"alignment="start"stretch={true}onClick={async () => {// Open Canva's built-in font picker dialogconst response = await requestFontSelection({selectedFontRef: selectedFont?.ref,});if (response.type === "completed") {setSelectedFont(response.font);resetSelectedFontStyleAndWeight(response.font);}}}disabled={disabled}>{selectedFont?.name || "Select a font"}</Button>{selectedFont?.previewUrl && (<Box background="neutralLow" padding="2u" width="full"><Rows spacing="0" align="center"><Box><ImageCardthumbnailUrl={selectedFont.previewUrl}alt={selectedFont.name}/></Box></Rows></Box>)}<Title size="small">Font options</Title><FormFieldlabel="Font weight"value={fontWeight}control={(props) => (<Select{...props}stretchonChange={(fontWeight) => {setTextConfig((prevState) => {return {...prevState,fontWeight,};});}}disabled={!selectedFont || availableFontWeights.length === 0}options={availableFontWeights}/>)}/><FormFieldlabel="Font style"value={fontStyle}control={(props) => (<SegmentedControl{...props}options={availableFontStyleOptions}value={fontStyle}onChange={(style) => {setTextConfig((prevState) => {return {...prevState,fontStyle: style,};});}}/>)}/><Buttonvariant="primary"onClick={() => {// Create a text element with the selected font and add it to the Canva designaddElement({type: "text",...textConfig,fontRef: selectedFont?.ref,children: [textConfig.text],});}}disabled={disabled}stretch>Add text element</Button></Rows></div>);};// Extract available font weights from a Canva Font object for display in UI componentsconst getFontWeights = (font?: Font,): {value: FontWeightName;label: FontWeightName;}[] => {return font? font.weights.map((w) => ({value: w.weight,label: w.weight,})): [];};// Extract available font styles for a specific weight from a Canva Font objectconst getFontStyles = (fontWeight: FontWeightName,font?: Font,): {value: FontStyle;label: FontStyle;}[] => {return font? (font.weights.find((w) => w.weight === fontWeight)?.styles.map((s) => ({ value: s, label: s })) ?? []): [];};
TYPESCRIPT
// For usage information, see the README.md file.import { AppUiProvider } from "@canva/app-ui-kit";import { createRoot } from "react-dom/client";import { App } from "./app";import "@canva/app-ui-kit/styles.css";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
# FontsDemonstrates how to find, select, and apply fonts to text elements. Shows font discovery, weight and style selection, and font picker integration for creating styled text with custom typography.For API reference docs and instructions on running this example, see: <https://www.canva.dev/docs/apps/examples/fonts/>.Related examples: See design_elements/text_elements for basic text insertion, or app_text_elements for text within app elements.NOTE: This example differs from what is expected for public apps to pass a Canva review:- Error handling for font loading and unavailable fonts is simplified for demonstration. Production apps must implement comprehensive error handling with retry logic and user feedback for API failures- Font fallback handling is not implemented. Production apps should provide fallback fonts and handle font loading failures gracefully- Text content is hardcoded for demonstration purposes only. Production apps should provide user input interfaces or dynamic content loading- 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?
- Join our Community Forum(opens in a new tab or window)
- Report issues with this example on GitHub(opens in a new tab or window)