Home App Docs Blog Github

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