0

The block code is as such:

  wp.blocks.registerBlockType('myblocks/gallery', {
  title: 'Gallery',
  icon: 'my-gallery',
  category: 'common',
  attributes: {
  },

  edit: props => {
    const [selectedFiles, setSelectedFiles] = useState([]);
    const [errorMessage, setErrorMessage] = useState('');

    const handleFiles = (files) => {
      
      for (let i = 0; i < files.length; i++) {
        if (validateFile(files[i])) {

        } else {
      

      //the code goes on...

It of course produces useState is not defined error, but I've no idea how to import it. When I attempt const {useState} = require( '@wordpress/element' );, I get a referenceError: require is not defined ; and I don't know where to place import { useState } from '@wordpress/element';

I'm probably misunderstanding the fundamental structure, since I'm new to Wordpress development, but I've no idea where to go from .

4
  • 1
    it looks like you're doing this without any build tools for JSX, which means things like return <p className={ classesVariable }>{ variable}</p> or import { useState } from @wordpress/element';` won't work. This isn't necessarily a WordPress thing but a modern JS/React thing. Also if you want a custom gallery, it's much easier to reuse the existing gallery with a block variant than to rebuild the entire thing from scratch as a brand new block, likewise if your gallery just looks different a block style will do the job just as well if not better
    – Tom J Nowell
    Commented May 4, 2023 at 17:38
  • Yeah I ended up adding JSX support. The gallery needs to automatically assign size to its elements based on their dimension so it seems to me writing one from scratch is easier than searching for a block that can do that. Commented May 5, 2023 at 11:13
  • 1
    You don't need to find a 3rd party block or create a new one. If the HTML is the same you can use a block style and then run JS or CSS on galleries with that class. Look at how Jetpack adds a tiled gallery option to the default core block without creating new gallery blocks.
    – Tom J Nowell
    Commented May 5, 2023 at 11:16
  • Oh man that is totally what I should have done. Thanks. Commented May 5, 2023 at 13:52

1 Answer 1

0

Okay, just lucked upon an answer. Added

const {
    element: {
        useState,
    },
} = wp;

at the top of the file, it seemingly works, though I still have no idea what is going on.

1
  • 1
    this is the same as const useState = window.wp.element.useState; but does it using object destructuring instead which is a modern javascript syntax. I fixed the indentation in the code as the broken indents make it harder to understand and read
    – Tom J Nowell
    Commented May 4, 2023 at 17:40

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.