I'm a bit of a rookie, so I may be looking at this all backwards - but if that is the case having someone point me in the right direction would be incredibly valuable!
I'm creating a few custom blocks and have been struggling through figuring out JSX, React, ES6 imports and exports, etc. But, I've noticed that I've been repeating myself a bit. For instance, many of my blocks will have a fairly identical option for selecting a background image and there are about 30 lines of code that I'm copy-pasting from block to block to allow for this.
My question is: Is there a way I can create a module or function that I can include instead of repeating this code over and over?
After a few hours I've just finished my first attempt, where I hit a stone wall trying to work out how to update/set the main block's properties from within another module. As when a new image is set, the image's ID and URL are added to the blocks attribute so they can be used later on. However, because I was processing the image and getting the ID in a separate module I couldn't save them to the main module/block's attributes.
I was thinking it could be possible to return all the needed values back to the main block and then set attributes there... but that felt like going further down the wrong path, so I thought I'd ask here instead!
Here's the code I'm looking to split off Into a separate module/file/element. It's all living in the "edit.js" file of a custom block at the moment - part of it is for getting the image's URL so it can be displayed in the editor, and the rest is for the actual UI in the settings sidebar/Inspector Controls
//Getting background images for editing preview
useEffect(
function () {
if (attributes.backgroundImageMB) {
async function go() {
const response = await apiFetch({
path: `/wp/v2/media/${attributes.backgroundImageMB}`,
method: "GET"
})
setAttributes({ backgroundImageMB_URL: response.media_details.sizes.full.source_url })
}
go()
}
},
[attributes.backgroundImageMB]
)
//Background image selection handling
function backgroundImageMB(x) {
setAttributes( { backgroundImageMB: x.id} )
}
And then:
<PanelRow>
<div className={"jcc-settings_image-preview"}>
<img src={attributes.backgroundImageMB_URL} />
</div>
<MediaUploadCheck>
<MediaUpload
className={"jcc-settings_image"}
onSelect={backgroundImageMB}
value={attributes.backgroundImageMB}
render={ ({ open }) => {
return <button onClick={open}>Choose Image</button>
}}
/>
</MediaUploadCheck>
</PanelRow>
<PanelRow>
<Button
className={"jcc-settings__rm-bg"}
variant="link"
onClick={ ( e ) => setAttributes( { backgroundImageMB: " ", backgroundImageMB_URL:" " } ) }
>
Remove Background
</Button>
</PanelRow>
<MediaPlaceholder>- maybe poke around a bit with that and see if it fulfills your needs.