Checking selection state

How to check if an app element is selected or not.

When creating app elements, an app usually needs to check if an element is selected or not. One use-case for this behavior is to show a Create element button when an element is not selected:

...but show an Update element button when an element is selected:

This guide explains how to check if an app element is selected or not.

Step 1: Track an element's selection state

Use React's useState hook to keep track of whether or not an app element is selected:

const [isSelected, setIsSelected] = React.useState(false);

By default, set the value of the hook to false, as an app element won't be selected when a user opens an app for the first time.

Step 2: Update an element's selection state

Apps can register a callback with the onAppElementChange method.

This callback runs when:

  • An app calls the setAppElementData method
  • A user selects an app element
  • A user deselects an app element

The callback receives an element parameter that is defined if an app element is selected. Therefore, if element is defined, isSelected should be set to true:

designInteraction.onAppElementChange((element) => {
if (element) {
setIsSelected(true);
} else {
setIsSelected(false);
}
});

Otherwise, isSelected should be set to false.

Step 3: Check if an element is selected

Use the isSelected variable to check if an app element is selected:

<button onClick={handleClick}>{isSelected ? "Update" : "Create"}</button>

You can use this variable to determine what content to render in an app's iframe or to determine the behavior of the app, such as what happens when a user clicks a button.

Example

import React from "react";
import { getDesignInteraction } from "@canva/design-interaction";
type AppElementData = {
date: string;
event: "updated" | "created";
};
export const App = () => {
const designInteraction = getDesignInteraction<AppElementData>();
const [isSelected, setIsSelected] = React.useState(false);
React.useEffect(() => {
designInteraction.registerRenderAppElement((data) => {
return [
{
type: "TEXT",
width: 300,
children: [`This element was ${data.event} at ${data.date}.`],
},
];
});
designInteraction.onAppElementChange((element) => {
if (element) {
setIsSelected(true);
} else {
setIsSelected(false);
}
});
}, [designInteraction]);
const handleClick = () => {
designInteraction.setAppElementData({
date: new Date().toString(),
event: isSelected ? "updated" : "created",
});
};
return (
<div>
<button onClick={handleClick}>{isSelected ? "Update" : "Create"}</button>
</div>
);
};