Actions
Custom actions are simply a custom JS functions that can be assigned by editors to button clicks.
Example action
Let's add a very simple action that displays alert
. Registering actions is very similar to registering components. They also have id
, label
and schema:
export const shopstoryConfig: Config = {
// ...
actions: [
{
id: "AlertAction",
label: "Alert action",
schema: [
{
prop: "text",
label: "Text",
type: "string",
defaultValue: "Hello"
}
]
}
],
}
The real action code should be added to ShopstoryProvider
:
import { ShopstoryProvider } from "@shopstory/core/react";
import { CustomComponent } from "../components/CustomComponent/CustomComponent";
const AlertAction = (props: { text: string }) => {
alert("Alert message: " + props.text);
}
export const DemoShopstoryProvider : React.FC = ({ children }) => {
return <ShopstoryProvider
actions={{
AlertAction
}}
>
{ children }
</ShopstoryProvider>
}
The values defined in the Shopstory sidebar will be passed as props to the AlertAction
function.
The result:
Running React hooks inside of actions
Sometimes you might have a need to access a React hook (https://reactjs.org/docs/hooks-intro.html) from a custom action. It's not safe to run React hook directly inside of the action code as it's not a React component. But don't worry, the hook can be safely called in the custom Shopstory Provider component and its content can be accessed from the action code, something like this:
export const DemoShopstoryProvider : React.FC = ({ children }) => {
const myContext = useContext(MyContext) // Running a React hook
return <ShopstoryProvider
actions={{
CustomAction: () => {
// accessing hook data in the action code
alert("Value from useContext hook: " + myContext.valueFromContext);
}
}}
>
{ children }
</ShopstoryProvider>
}
Last updated