Create a Repeater Field in Block Settings (Inspector Controls)

I got some experience with repeaters when I was developing it for my Simple Fields plugin and I also have a whole tutorial about using them in Plugin Sidebars.

But recently I faced with another challenge – I needed a repeater field as a block setting inside Inspector Controls (in my Simple Carousel Block it was intended to configure multiple responsive breakpoints). Like this:

Repeater Field in Gutenberg Block Settings
It is exactly how “Responsive” option looks and works in my Gutenberg carousel block.

And that is when the things didn’t go as expected at all. So let me just break it down for you if you’d ever face with something like this.

The first thing you need to know is no matter how many subfields your repeater has, in any case you need to specify it in your block.json just as an array.

"attributes": {
	"breakpoints": {
		"type": "array",
		"default" : []
	}
}

When working with repeater data in our block edit() function we can not just refer to attributes.breakpoints directly, it doesn’t work that way, we have to use useState() hook which we can import from @wordpress/element.

You can also see that I pass attribute.breakpoints as a default value of useState() hook.

edit: ( { attributes, setAttributes } ) => {
	
	const [breakpoints, setBreakpoints] = useState( attributes.breakpoints );

Then inside breakpoints.map( row, index ) loop we are about to do some interesting stuff. We’re not only changing the state using setBreakpoints() but also changing the attribute value with setAttributes(). A similar code you can find in this example.

<NumberControl
	label="Min screen width (px)"
	value={ breakpoints[index][ 'breakpoint' ] }
	labelPosition="side"
	onChange={ ( value ) => {

		setBreakpoints( prevValue => {
			const newValue = prevValue.map((row, innerIndex) => {
				return innerIndex === index ? {...row, ['breakpoint']: value} : row
			});
			setAttributes( { breakpoints: newValue } )
			return newValue
		} )

	} }
/>

And that’s pretty much it. If you think that the last piece of code could be written in a more elegant way, please let me know in the comments below.

Misha Rudrastyh

Misha Rudrastyh

Hey guys and welcome to my website. For more than 10 years I've been doing my best to share with you some superb WordPress guides and tips for free.

Need some developer help? Contact me

Follow me on X