Home > Software design >  How to rerender inside of .map() list using Gutenberg withSelect
How to rerender inside of .map() list using Gutenberg withSelect

Time:04-07

I'm creating table of content Gutenberg custom block which reactive reflect h2 text. Outside of map(), it works. but inside not working.

Please let me know how to modify this code.

thanks.

import { registerBlockType } from "@wordpress/blocks";
import { withSelect, select } from "@wordpress/data";

registerBlockType("theme/toc", {
  title: "TOC",
  icon: "list-view",
  category: "layout",
  edit: withSelect((select) => {
    return {
      blocks: select("core/block-editor").getBlocks(),
    };
  })(Edit),
  save: () => {
    return null;
  },
});

export function Edit(props) {
  const { blocks = [] } = props;
  const headings = [];
  blocks.forEach((el) => {
    if (!(el.name === "core/heading" && el.attributes.level === 2)) {
      return;
    }
    headings.push(el.attributes.content);
  });

  return (
    <div>
      <p>{headings[0]}</p> // this line works
      <ol>
        {headings.map((h2, i) => { // not working
          <li key={i}>
            <a>{h2}</a>
          </li>;
        })}
      </ol>
    </div>
  );
}

CodePudding user response:

Simply remove the curly braces so the JSXElemnt can be returned from the map function.

 <ol>
    {headings.map((h2, i) =>
      <li key={i}>
        <a>{h2}</a>
      </li>;
    )}
  </ol>

something else to note is it's not advised to use the element index i as the key value. you may want to use a more unique value like id from the element you're looping through.

  • Related