Shopstory
  • Overview
  • Getting started
    • Installation
    • Connecting CMS
      • Contentful
      • Sanity
    • Displaying content
    • Content modeling with Shopstory
  • Devices and breakpoints
  • Design tokens
    • Colors
    • Spacings
    • Fonts
    • Page containers
      • Margins
      • Max width
    • Aspect ratios
    • Missing tokens
  • Custom code
    • Components
    • Buttons
    • Actions
    • Links
  • Resources
  • Image
  • Analytics
  • Schema reference
  • CMS Guides
    • Contentful
    • Sanity
Powered by GitBook
On this page
  • Example action
  • Running React hooks inside of actions
  1. Custom code

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

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>
}
PreviousButtonsNextLinks

Last updated 2 years ago

Sometimes you might have a need to access a React hook () 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:

https://reactjs.org/docs/hooks-intro.html