Examples
App elements
Assets and media
Fundamentals
Intents
Design interaction
Drag and drop
Design elements
Localization
Content replacement
Table elements
Add structured table elements with rows and columns.
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 table_elementsSHELL -
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 { useState, useCallback } from "react";import * as styles from "styles/components.css";import {Alert,Button,ColorSelector,Column,Columns,FormField,NumberInput,PlusIcon,Rows,Text,TextInput,Title,} from "@canva/app-ui-kit";import type { CellState, TableState } from "./use_table_hook";import { useTable } from "./use_table_hook";import { useAddElement } from "utils/use_add_element";const initialState: TableState = {rowCount: 4,columnCount: 5,cells: [{rowPos: 1,columnPos: 1,colSpan: 3,rowSpan: 2,text: "2x3",fillColor: "#deffdb",},{rowPos: 1,columnPos: 4,rowSpan: 2,text: "2x1",fillColor: "#dbf1ff",},{ rowPos: 4, columnPos: 1, colSpan: 2, text: "1x2" },{ rowPos: 3, columnPos: 5, fillColor: "#ffa000" },],};const CellElement = ({index,value: state,onChange,}: {index: number;value: CellState;onChange: (value: CellState) => void;}) => {return (<Rows spacing="1u"><Title size="small">Cell #{index}</Title><Columns spacing="1u"><Column width="1/2"><FormFieldlabel="Row position"value={state.rowPos}control={(props) => (<NumberInput{...props}onChange={(value) => {onChange({ ...state, rowPos: value });}}/>)}/></Column><Column width="1/2"><FormFieldlabel="Column position"value={state.columnPos}control={(props) => (<NumberInput{...props}onChange={(value) => {onChange({ ...state, columnPos: value });}}/>)}/></Column></Columns><Columns spacing="1u"><Column width="1/2"><FormFieldlabel="rowSpan"value={state.rowSpan}control={(props) => (<NumberInput{...props}onChange={(value) => {onChange({...state,rowSpan: value,});}}/>)}/></Column><Column width="1/2"><FormFieldlabel="colSpan"value={state.colSpan}control={(props) => (<NumberInput{...props}onChange={(value) => {onChange({...state,colSpan: value,});}}/>)}/></Column></Columns><Columns spacing="1u"><Column width="content"><FormFieldlabel="Text content"value={state.text}control={(props) => (<TextInput{...props}onChange={(value) => {onChange({...state,text: value,});}}/>)}/></Column><Column width="content"><FormFieldlabel="Fill color"control={(props) => (<ColorSelector{...props}color={state.fillColor || "#FFFFFF"}onChange={(value) => {onChange({...state,fillColor: value === "#FFFFFF" ? undefined : value,});}}/>)}/></Column></Columns></Rows>);};export const App = () => {const tableState = useTable(initialState);const [submissionError, setSubmissionError] = useState("");const addElement = useAddElement();const onClick = useCallback(async () => {try {await addElement(tableState.toElement());} catch (e) {if (e instanceof Error) {setSubmissionError(e.message);}}}, [tableState]);const onAddCell = useCallback(() => {tableState.cells = [...(tableState.cells || []), {}];}, []);return (<div className={styles.scrollContainer}><Rows spacing="3u"><Text>This example demonstrates how apps can add table elements to a design.</Text>{(tableState.error || submissionError) && (<Alert tone="critical">{tableState.error || submissionError}</Alert>)}<Columns spacing="3u"><Column width="1/2"><FormFieldlabel="Total rows"value={tableState.rowCount}control={(props) => (<NumberInput{...props}onChange={(value) => {tableState.rowCount = value;}}/>)}/></Column><Column width="1/2"><FormFieldlabel="Total columns"value={tableState.columnCount}control={(props) => (<NumberInput{...props}onChange={(value) => {tableState.columnCount = value;}}/>)}/></Column></Columns><Title size="medium">Cell customizations</Title>{tableState.cells?.map((value, index) => (<CellElementkey={`cell-${index}`}index={index}value={value}onChange={(value) => {const cells = tableState.cells?.slice() || [];cells[index] = value;tableState.cells = cells;}}/>))}<Button variant="secondary" onClick={onAddCell} icon={PlusIcon}>New custom cell</Button><Button variant="primary" onClick={onClick} stretch>Add element</Button></Rows></div>);};
TYPESCRIPT
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();if (module.hot) {module.hot.accept("./app", render);}
TYPESCRIPT
import { TableWrapper } from "utils/table_wrapper";import type { TableElement } from "@canva/design";import { useCallback, useEffect, useState } from "react";/*** The current state of a cell within a table.*/export type CellState = {/*** The position of the cell in the row, starting from `1`.*/rowPos?: number;/*** The position of the cell in the column, starting from `1`.*/columnPos?: number;/*** The number of rows that the cell should span.*/rowSpan?: number;/*** The number of columns that the cell should span.*/colSpan?: number;/*** The text content of the cell.*/text?: string;/*** The background color of the cell as a hex code. The hex code be six characters long* and preceded with a `#`. For example, `#ff0099`.*/fillColor?: string;};/*** The current state of a table.*/export type TableState = {/*** The number of rows in the table.*/rowCount?: number;/*** The number of columns in the table.*/columnCount?: number;/*** By default, a table's cells are empty. You can use this property to define the* content and appearance of cells.*/cells?: CellState[];/*** An error message to indicate that the table is in an error state.*/error?: string;};/*** A hook that simplifies the creation of a table and the management of a table's state.* @param initialState The initial state of the table, such as the number of rows and columns it has.* @returns The current state of the table and methods for interacting with the table.*/export const useTable = (initialState: TableState,): TableState & {/*** Converts the table state into a {@link TableElement}. The result can then* be passed into the `addElementAtPoint` or `addElementAtCursor` method.*/toElement(): TableElement;} => {const [rowCount, setRowCount] = useState(initialState.rowCount);const [columnCount, setColumnCount] = useState(initialState.columnCount);const [cells, setCells] = useState<CellState[]>(initialState.cells || []);const [error, setError] = useState<string | undefined>();const [wrapper, setWrapper] = useState<TableWrapper>(TableWrapper.create(rowCount || 1, columnCount || 1),);const toElement = useCallback(() => wrapper.toElement(), [wrapper]);useEffect(() => {setError(undefined);if (typeof rowCount !== "number" || typeof columnCount !== "number") {return;}try {const newWrapper = TableWrapper.create(rowCount, columnCount);setWrapper(newWrapper);} catch (e) {if (e instanceof Error) {setError(e.message);}}}, [rowCount, columnCount]);useEffect(() => {setError(undefined);try {for (const cell of cells) {if (typeof cell.rowPos === "number" &&typeof cell.columnPos === "number") {wrapper.setCellDetails(cell.rowPos, cell.columnPos, {rowSpan: cell.rowSpan,colSpan: cell.colSpan,type: "string",value: cell.text || "",attributes: cell.fillColor? { backgroundColor: cell.fillColor }: undefined,});}}} catch (e) {if (e instanceof Error) {setError(e.message);}}}, [cells, wrapper]);return {get rowCount() {return rowCount;},set rowCount(value) {setRowCount(value);},get columnCount() {return columnCount;},set columnCount(value) {setColumnCount(value);},get cells() {return cells;},set cells(value) {setCells(value);},get error() {return error;},toElement,};};
TYPESCRIPT
# Table elementsDemonstrates how to create table elements with configurable rows, columns, cell spans, and formatting. Shows table structure definition, cell customization, and table insertion patterns.For API reference docs and instructions on running this example, see: https://www.canva.dev/docs/apps/examples/table-elements/.NOTE: This example differs from what is expected for public apps to pass a Canva review:- Table structure and data are hardcoded for demonstration purposes only. Production apps should provide user input interfaces or dynamic content loading and table editing interfaces- Data import and cell validation capabilities are not implemented. Production apps should include data import capabilities and cell validation- 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?
- 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)