admin管理员组

文章数量:1122832

I'm making a review widget that comes as a shortcode and Gutenberg block. The shortcode part was easy as I have built many shortcodes before, but I'm stuck on building my first Gutenberg block.

More specifically, I've learned how to build a block that outputs div with custom class, but I can't find how to add a custom div attribute anywhere...

Here's the code responsible for block output:

return el( 'div',
      {
         className: 'review-widget',
      }

   ); // End return

and this outputs

<div class="review-widget"></div>

properly.

However, I need to output a div like this:

<div class="review-widget" data-limit="10"></div>

but I'm having a hard time adding the data-limit="10" to the div.

I've tried:

return el( 'div',
      {
         className: 'review-widget',
         data-limit: 10
      }

   ); // End return

but it doesn't work...

Any ideas would be appreciated :)

I'm making a review widget that comes as a shortcode and Gutenberg block. The shortcode part was easy as I have built many shortcodes before, but I'm stuck on building my first Gutenberg block.

More specifically, I've learned how to build a block that outputs div with custom class, but I can't find how to add a custom div attribute anywhere...

Here's the code responsible for block output:

return el( 'div',
      {
         className: 'review-widget',
      }

   ); // End return

and this outputs

<div class="review-widget"></div>

properly.

However, I need to output a div like this:

<div class="review-widget" data-limit="10"></div>

but I'm having a hard time adding the data-limit="10" to the div.

I've tried:

return el( 'div',
      {
         className: 'review-widget',
         data-limit: 10
      }

   ); // End return

but it doesn't work...

Any ideas would be appreciated :)

Share Improve this question asked May 13, 2020 at 11:07 StefanRStefanR 133 bronze badges
Add a comment  | 

2 Answers 2

Reset to default 0

You could try returning JSX, skipping the el part:

return (
    <div
        className='review-widget'
        data-limit='10'
    >
    </div>
);

It may also be that you need to quote the 10 in your original el example.

I found my answer here: https://stackoverflow.com/questions/43410377/how-to-add-data-attribute-without-value-in-react-create-element \o/

Both the attribute name and the attribute value should be wrapped in quotes:

return el( 'div',
      {
         className: 'review-widget',
         'data-limit': '10'
      }

   ); // End return

本文标签: javascriptHow to return div with custom attributes(Coding a Gutenberg Block)