Sitecore NextJS Dynamic Placeholders

159 Views Asked by At

I need to dynamically generate 5, 10 or 15 placeholders. I have created a placeholder and given it the key: text-container-{*}

I added this placeholder to my Rendering and set the Parameter Template to a Rendering parameter which inherits from IDynamicPlaceholder

My Next JS code is below:

interface ComponentProps {
  rendering: ComponentRendering & { params: ComponentParams };
  params: ComponentParams;
}
const array: number[] = [1, 2, 3, 4, 5]; // To generate the Placeholder 5 times

const TextOrgContainer = (props: ComponentProps): JSX.Element => {
return (
    <div>
      {array?.map((item, key) => {
        const phKey = `text-container-${props.params.DynamicPlaceholderId}`;
        return <Placeholder key={key} name={phKey} rendering={props.rendering} />;
      })}
    </div>
  );
};

I see 5 placeholders generated, but all have the same Id: text-container-3

As a result, if I add a Rendering to one Placeholder, all end up having the same rendering on Save/Refresh.

I also tried props.params.EnabledPlaceholders, but props.params.EnabledPlaceholders is always undefined.

If I replace ${props.params.DynamicPlaceholderId} with ${item}, I get the error:

A rendering error occurred: Cannot read properties of undefined (reading 'attributes').

What am I missing?

1

There are 1 best solutions below

0
On

I worked with dynamic placeholder but that need to different name and associated placeholder name from sitecore instance, i don't think if you want to add placeholder dynamically from frontend side will work.

If you really want this scenario what you can do it create placeholders like text-container-1 to text-container-n (n times) and you can do like this.

interface ComponentProps {
  rendering: ComponentRendering & { params: ComponentParams };
  params: ComponentParams;
}
const array: number[] = [1, 2, 3, 4, 5]; // To generate the Placeholder 5 times

const TextOrgContainer = (props: ComponentProps): JSX.Element => {
return (
    <div>
      {array?.map((item, index) => {
        const phKey = `text-container-${index}`;
        return <Placeholder key={index} name={phKey} rendering={props.rendering} />;
      })}
    </div>
  );
};