How do I limit the number of list items a user can add to a custom component?

Let’s say you made a custom react component for use in Builder that has some properties that rely on user input. If one of them is a list item, you might want to limit the number of items in that list to prevent a user from adding way too many. An example might be images in a carousel, or number of tabs.

How can we do that? Luckily you can pass a function to onChange and validate the length of the list there. Here is a sample of how you might want to do that:

onChange: (options) => {
  if (options.get('myList').length > 6) {
    options.set('myList', options.get('myList').slice(0, 6))
    alert('maximum items is 6, delete items to continue')
  }
}

Here is an example of the onChange in one of our components: https://github.com/BuilderIO/builder/blob/047a982c4836cccee36f7fcc7e8ebac8e3960cd4/packages/widgets/src/components/Carousel.tsx#L374

Note: Just an FYI, that function is stringified and evaluated in the context of the parent window, so don’t try to use any references to other variables or functions that you might have within the file that your component is written in.

1 Like

You can also use the regex property on the input to validate what someone enters as a value for the input. This works for any input that results in a string value. If you are able to craft a regex to validate the value, then this approach is a nice way to go. Check out the regex definition here for tips on how to use it: builder/builder.class.ts at master · BuilderIO/builder · GitHub

Nice thanks for sharing, is there anyway we could disable the button to add items? @korey

Hello @saura,

You can try something like below example

Builder.registerComponent('SublistWithLimit', {
  name: 'SublistWithLimit',
  inputs: [
    {
      name: 'list1',
      type: 'list',
      onChange: (options) => {
        if (options.get('list1').length > 0) {
          options.set('list1', options.get('list1').slice(0, 0))
          alert('maximum items is 0, delete items to continue')
        }
      },
      subFields: [
        {
          name: 'subList',
          type: 'list',
          subFields: [
            {
              name: 'subListText',
              type: 'text',
            },
          ],
        },
      ],
    },
  ],
})

Yeah we did this but it didn’t work once deployed, super random tbh.

Hello @saura,

Could you please confirm if you deployed your application on Vercel or Cloudfront?

Vercel! :smiley: jejejejeeeeee

Hello @saura,

It seems like this issue might be related to Vercel, as we’ve encountered similar issues with Vercel deployments in the past. Unfortunately, we don’t have a direct solution for this problem at the moment. However, rest assured that we’re actively looking for workarounds. I’ll keep you updated if we find any solutions or workarounds for this issue.

Thanks,