theme development – How to add InnerBlock multiple times in the same block

Question

When I click a button to add a new tab, I would like to have an <InnerBlock /> so I can add other blocks within the tab. Trying this does not work as the same seems to be in all the dynamically created tabs.

import "./index.css";
import { registerBlockType } from "wordpress user/blocks";
import { useState } from "react";
import {
  RichText,
  InnerBlocks,
} from "wordpress user/block-editor";
import { Button } from "wordpress user/components";
const __ = wp.i18n.__;

registerBlockType("custom/tabs", {
  title: __("Tabbed Blocks", "custom-blocks"),
  description: __("Tabbed content blocks", "custom-blocks"),
  icon: "smiley",
  category: "custom-category",
  keywords: [__("tabs", "custom-blocks"), __("repeat", "custom-blocks")],
  attributes: {
    tabs: {
      type: "array",
      default: [""],
    },
  },

  edit: (props) => {
    const {
      attributes: { tabs },
      setAttributes,
    } = props;

    const [currentTab, setCurrentTab] = useState(0);

    const onTabClick = (index) => {
      setCurrentTab(index);
    };

    return (
      <>
        <div className="simple-tabs">
          <div className="tabs">
            {tabs.map((tab, index) => (
              <RichText
                tagName="button"
                value={tab}
                className={currentTab == index ? `active` : ""}
                onChange={(newValue) => {
                  const newTabs = tabs.concat([]);
                  newTabs[index] = newValue;
                  setAttributes({ tabs: newTabs });
                }}
                onClick={() => onTabClick(index)}
              />
            ))}
          </div>

          {tabs.map((tab, index) => {
            if (index == currentTab) {
              //return <div>Tab content {index}</div>;
              return <InnerBlocks />;
            }
          })}
        </div>
        <Button
          isPrimary
          onClick={() => {
            setAttributes({ tabs: tabs.concat([""]) });
          }}
        >
          Add Tab
        </Button>
      </>
    );
  },
  save: (props) => {
   return <InnerBlocks.Content />;
  },
});

0
user8463989 1 week 2021-11-23T13:23:09-05:00 0 Answers 0 views 0

Leave an answer

Browse
Browse