Skip to content

[Bug]: Fragment child elements are not transformed correctly when using @babel/plugin-transform-react-constant-elements #16449

@mo36924

Description

@mo36924

💻

  • Would you like to work on a fix?

How are you using Babel?

Programmatic API (babel.transform, babel.parse)

Input code

const a = () => <><div>a</div></>

Configuration file name

babel.config.json

Configuration

{
  "parserOpts": {
    "plugins": ["jsx"]
  },
  "presets": [],
  "plugins": ["@babel/plugin-transform-react-constant-elements"]
}

Current and expected behavior

Expected:

var _div;
const a = () => <>{_div || (_div = <div>a</div>)}</>;

or

var _Fragment;;
const a = () => _Fragment || (_Fragment = <><div>a</div></>);

Received:

var _div;
const a = () => <>_div || (_div = <div>a</div>)</>;

Environment

  • System:
    OS: macOS 14.4.1
  • Binaries:
    Node: 20.11.1 - ~/.proto/shims/node
    Yarn: 1.22.19 - ~/.nvm/versions/node/v18.18.2/bin/yarn
    npm: 10.2.4 - ~/.proto/shims/npm
    bun: 1.0.29 - ~/.proto/shims/bun
  • npmPackages:
    @babel/plugin-transform-react-constant-elements: ^7.24.1 => 7.24.1
    @babel/preset-typescript: ^7.24.1 => 7.24.1

Possible solution

if (
path.parentPath.isJSXElement() ||
path.parentPath.isJSXAttribute()
) {
replacement = t.jsxExpressionContainer(replacement);
}

Although the entire fragment cannot be made constant, the transformation of child elements works fine using the code below.

if (
  path.parentPath.isJSXFragment() ||
  path.parentPath.isJSXElement() ||
  path.parentPath.isJSXAttribute()
) {
  replacement = t.jsxExpressionContainer(replacement);
}

Additional context

No response

Metadata

Metadata

Assignees

No one assigned

    Labels

    outdatedA closed issue/PR that is archived due to age. Recommended to make a new issue

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions