reactjsshopifypolaris

Shopify Polaris: How to make an item active in ActionList?


I have an ActionList with some contents. I want to make active: true when an item is clicked. And I'm struggling how to do it using Shopify Polaris's ActionList. I could get the index which I clicked. But I'm not sure how to use the index to an active: true and where. If you could give me some advice, it really helps me.

import React, { useCallback, useState } from "react";
import { ActionList, Button, Icon, Popover } from "@shopify/polaris";
import { TickSmallMinor, ImportMinor } from "@shopify/polaris-icons";

const actions = [
  {
    content: "Import file"
  },
  {
    content: "Export file"
  },
  {
    content: "Export file2"
  },
  {
    content: "Export file3"
  },
  {
    content: "Export file4"
  }
];

export default function ActionListWithSuffixExample() {
  const [active, setActive] = useState(true);
  const [isClicked, setIsClicked] = useState(Array(actions.length).fill(false));
  console.log(actions.length);

  const toggleActive = useCallback(() => setActive((active) => !active), []);

  const activator = (
    <Button onClick={toggleActive} disclosure>
      More actions
    </Button>
  );

  const handleClick = (index) => {
    console.log("index", index);
    setIsClicked((prev) => [
      ...prev.slice(0, index),
      !prev[index],
      ...prev.slice(index + 1)
    ]);
  };

  return (
    <div style={{ height: "200px" }}>
      <Popover
        active={active}
        activator={activator}
        autofocusTarget="first-node"
        onClose={toggleActive}
      >
        <ActionList
          actionRole="menuitem"
          items={actions.map((a, i) => ({
            onAction: () => handleClick(i),
            active: isClicked,
            content: a.content,
            icon: ImportMinor,
            suffix: <Icon source={TickSmallMinor} />
          }))}
        />
      </Popover>
    </div>
  );
}

https://codesandbox.io/embed/lively-tdd-fp49cl?fontsize=14&hidenavigation=1&theme=dark


Solution

  • You forgot to put the index in the active property

                active: isClicked[i],