I'm creating a custom Gutenberg block using node.js and REACT. Eventually this will be a Bootstrap slider that can have slides added dynamically. For each slide the user needs to upload a video or image. I am doing this using the built-in component that is part of @wordpress/block-editor.
I've added 3 <MediaUpload>
components in the <InspectorControls>
that will display in the right block controls column in WordPress.
They work by calling an "onChange" function that updates the backgroundImage attribute that is originally set in block.json.
<InspectorControls>
<PanelRow>
<fieldset class="media-upload">
<strong>Select slide 1 video or image:</strong>
<MediaUpload
onSelect={onImageSelect}
type={ [ 'image', 'video' ] }
value={backgroundImage}
render={({ open }) => (
<button onClick={open}>
Upload Image!
</button>
)}
/>
</fieldset>
<fieldset class="media-upload">
<strong>Select slide 2 video or image:</strong>
<MediaUpload
onSelect={onImageSelect}
type={ [ 'image', 'video' ] }
value={backgroundImage}
render={({ open }) => (
<button onClick={open}>
Upload Image!
</button>
)}
/>
</fieldset>
<fieldset class="media-upload">
<strong>Select slide 3 video or image:</strong>
<MediaUpload
onSelect={onImageSelect}
type={ [ 'image', 'video' ] }
value={backgroundImage}
render={({ open }) => (
<button onClick={open}>
Upload Image!
</button>
)}
/>
</fieldset>
</PanelRow>
</InspectorControls>
EDIT. I'm updating this question now that Teemu has clarified that variable names in JavaScript can't be dynamic.
To simplify the question. How can I write the below 3 functions in less lines of code? I think I need to increment the attribute backgroundImage[1] using a loop, but I can't figure out how to write this?
const onImageSelect1 = ( imageObject ) => {
setAttributes( { backgroundImage1: imageObject.url } )
}
const onImageSelect2 = ( imageObject ) => {
setAttributes( { backgroundImage2: imageObject.url } )
}
const onImageSelect3 = ( imageObject ) => {
setAttributes( { backgroundImage3: imageObject.url } )
}