Brian
Brian

Reputation: 581

How to prepend an element to a React element?

I am new to React and am trying to make some modifications to a WordPress block.

If I do this:

const addContentTypeMarkup = ( element, blockType, attributes ) => {
    // Do nothing if it's another block than our defined ones.
    if ( ! enableBlockContentTypeAttribute.includes( blockType.name ) ) {
        return element;
    }
    if ( attributes.contenttitle) {
        return (
            <div className="test">
            {element}
            </div>
    )
    } else {
        return element;
    }
};
addFilter( 'blocks.getSaveElement', 'my-mods/add-content-type-markup', addContentTypeMarkup);

then all is fine. But I don't want to just return the element wrapped in a div. I just want to add content before the element. If I try:

return (
            <h3>test</h3>
            {element}
    )

Then I get compile error:

ERROR in ./js/block.js
Module build failed: SyntaxError: Unexpected token, expected , (149:12)

  147 |         return (
  148 |             <h3>test</h3>
> 149 |             {element}
      |             ^
  150 |     )
  151 |     } else {
  152 |         return element;

Being new to React I am sure I am overlooking some simple concept.

Upvotes: 0

Views: 597

Answers (3)

IceMetalPunk
IceMetalPunk

Reputation: 5556

When you return JSX, it NEEDS to be wrapped in an element. Usually we use divs or spans, but if you don't want an actual element, you can use fragments instead. A fragment is a kind of "pseudo-element": it doesn't actually render an element to the DOM, but acts as a wrapper for returned JSX.

The long way to do this:

return (
    <React.Fragment>
        <h3>Test</h3>
        {element}
    </React.Fragment>
);

The newer short syntax:

return (
    <>
        <h3>Test</h3>
        {element}
    </>
);

Upvotes: 0

kind user
kind user

Reputation: 41893

Use Fragment instead, it won't be rendered and will not be added into the DOM tree.

return (
   <>
     <h3>test</h3>
     {element}
   </>
);

You can also use React.Fragment syntax:

return (
   <React.Fragment>
     <h3>test</h3>
     {element}
   </React.Fragment>
);

Upvotes: 2

Gabriel Ferreira
Gabriel Ferreira

Reputation: 351

You need a wrapper for these elements, you can use a div or the react Fragment component.

<div>
  <h3>test</h3>
  {element}
</div>

or

<React.Fragment>
  <h3>test</h3>
  {element}
</React.Fragment>

Upvotes: 0

Related Questions