1

I'm developing a custom gutenberg block that conditionally loads a core/video or a core/image block. I'm not usign allowedBlocks in InnerBlocks beacuse I don't want the user has to click the + button to insert the innerblock content. So I'm loading conditionally two templates, one for video and one for image.

The problem is that when the user selects the button for core/image, a placeholder is rendered instead of MediaUpload, and MediaUpload apperas only after the user clicks on the placeholder. I want to remove this ckick step and render immediately the MediaUpload.

placeholder in innerblocks

Here's my edit.js

export default function BFSingleImageVideoEdit({ attributes, setAttributes }) {

    const ChooseContent = () => {
      let content = ''
      if (attributes.renderedContent == "image") {
        const IMAGE_TEMPLATE = [
          [ 'core/image', {} ],
        ];
        content = <InnerBlocks template={ IMAGE_TEMPLATE } templateLock="all" />
      }
      else if (attributes.renderedContent == "video") {
        const VIDEO_TEMPLATE = [
          [ 'core/video', {} ],
        ];
        content = <InnerBlocks template={ VIDEO_TEMPLATE } templateLock="all" />
      } 
      else if (attributes.renderedContent == false) {
          content =
          <div>
              <h3>Choose an image or a video</h3>
              <Button variant="primary" onClick={ () => setAttributes({renderedContent: 'image'}) }>Image</Button>
              <Button variant="primary" onClick={ () => setAttributes({renderedContent: 'video'}) }>Video</Button>
          </div>
       }
      return content
    }

    return (
      <div { ...useBlockProps() }>
        <BlockControls></BlockControls>
        <ChooseContent />
        { attributes.renderedContent ? <Button variant="primary" onClick={ () => setAttributes({renderedContent: false}) }><>&#8592;</> back</Button> : null }
      </div>
    )
}

1 Answer 1

0

Unfortunately, there is no easy solution. You could use editor.BlockEdit hook to change default core/image Edit component, and copy the code from current trunk version, and change there to not use MediaPlaceholder, but MediaUpload wrapped in MediaUploadCheck. However, that would create problem that all core/image blocks would be changed and it would not be futureproof, since code that you copied may change over time. You can solve the former by testing using getBlockParents selector and if immediate parent (0 element of array) is your block that change only that instance in the filter.

However, I would create another block and use inside its edit:

<MediaUploadCheck>
  <MediaUpload />
</MediaUploadCheck>

to automatically open image uploader. This block would be instead of core/image in your template.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.