Element actions for code components

Overview

Code component elements can expose functions that can be triggered in your app by interactions.

For example, the built-in Form component exposes an action called “Clear fields”. This allows you to clear fields from any kind of interaction, such as a click on a custom button or after form submission.

To expose element actions, you’ll need to:

  1. Define functions on a code component’s ref with React’s useImperativeHandle.
  2. During code component registration, add metadata about the functions in refActions.
Are element actions the same as custom actions?

No, element actions are not the same as custom actions. Custom actions are controls that show up in Plasmic Studio. This page is about element actions, which are functions that can be triggered in your app by interactions.

Example

Let’s build an simple counter code component. It displays the count but only allows it to be manipulated by element actions.

Try copying the below code into your app host. Then, in Plasmic Studio, insert a Counter and a few buttons that trigger the element actions.

Code component with useImperativeHandle

Copy
import { forwardRef, useImperativeHandle, useState } from 'react';
interface CounterActions {
increment(): void;
decrement(): void;
set(count: number): void;
}
export const Counter = forwardRef<CounterActions>(function Counter(_props, ref) {
const [count, setCount] = useState<number>(0);
useImperativeHandle(
ref,
() => {
return {
increment() {
setCount((count) => count + 1);
},
decrement() {
setCount((count) => count - 1);
},
set(count: number) {
setCount(count);
}
};
},
[setCount]
);
return <span>{count}</span>;
});

Code component registration with refActions

Copy
PLASMIC.registerComponent(Counter, {
name: 'Counter',
props: {},
refActions: {
increment: {
description: 'Add one to the counter',
argTypes: []
},
decrement: {
description: 'Subtract one from the counter',
argTypes: []
},
set: {
description: 'Set the counter to any number',
argTypes: [
{
name: 'count',
type: 'number'
}
]
}
}
});
Was this page helpful?

Give feedback on this page