React component name from factory

521 views Asked by At

I have two components:

const CustomSelfDefinedComponent = () => <React.Fragment />;
const CustomSelfDefinedViaFactoryComponent = (() => () => <React.Fragment />)();

on shallow rendering I get next:

        <CustomSelfDefinedComponent />
        <Component />

Can anyone point me why in second case I don't have CustomSelfDefinedViaFactoryComponent as a component name in a snapshot?

I see the reason at the fact that it compiles as : [BABEL PLAYGROUND]

"use strict";

var CustomSelfDefinedComponent = function CustomSelfDefinedComponent() {
  return /*#__PURE__*/React.createElement(React.Fragment, null);
};

var CustomSelfDefinedViaFactoryComponent = function () {
  return function () {
    return /*#__PURE__*/React.createElement(React.Fragment, null);
  };
}();

Any solutions?

1

There are 1 answers

1
fantactuka On BEST ANSWER

I suppose React relies on function.name to get default component name, so in first case

const CustomSelfDefinedComponent = () => <React.Fragment />;
CustomSelfDefinedComponent.name -> "CustomSelfDefinedComponent"

while in second anonymous function returned and name = ""

To solve that factory function can have explicit displayName argument:

const factory = (..., displayName) => {
  const NewComponent = () => { ... }
  NewComponent.displayName = displayName
  return NewComponent
}

not sure if there's a babel plugin that can simplify it