pugjs / babel-plugin-transform-react-pug

A plugin for transpiling pug templates to jsx
MIT License
811 stars 47 forks source link

Wrap with <React.Fragment>, if templates returns multiple elements #26

Closed yuheiy closed 6 years ago

yuheiy commented 6 years ago

source:

import React from "react";

class MyComponent extends React.Component {
  render() {
    return pug`
      div foo
      | bar
      div baz
    `;
  }
}

compile to:

import React from "react";

class MyComponent extends React.Component {
  render() {
    return React.createElement(
      React.Fragment,
      null,
      React.createElement(
        "div",
        null,
        "foo"
      ),
      "bar",
      React.createElement(
        "div",
        null,
        "baz"
      )
    );
  }
}
yuheiy commented 6 years ago

We can write like this:

import React from "react";

class MyComponent extends React.Component {
  render() {
    return pug`
      React.Fragment
        div foo
        | bar
        div baz
    `;
  }
}

I thought that should not be implicitly wrapped with <React.Fragment>. Sorry.

ForbesLindesay commented 6 years ago

We should do this automatically for people.

pjungwir commented 6 years ago

@yuheiy have you tested your suggestion? I get this error, because of the period:

Element type is invalid: expected a string (for built-in components) or a class/function (for composite components) but got: object.

(See this similar issue with haml-jsx-loader.)

I don't mind wrapping everything in React.Fragment by hand, but of course only if it works. :-)

This does work for me:

return <React.Fragment>
  {pug`
    .fixed-toolbar hi
    .container.under-toolbar
  `}
</React.Fragment>;

But then I get a loud warning with a stack trace:

Warning: Each child in an array or iterator should have a unique "key" prop.
ForbesLindesay commented 6 years ago

Yes, this doesn't currently work, and we should just swap from returning an array to returning a React Fragment.

ezhlobo commented 6 years ago

I'm reopening this issue until we bump new version.

ForbesLindesay commented 6 years ago

Released as 6.0.0