react-element-to-jsx-string icon indicating copy to clipboard operation
react-element-to-jsx-string copied to clipboard

formatReactElementNode: convert displayName to String

Open ckknight opened this issue 5 years ago • 3 comments

If the displayName for a component turns out to be a symbol for some reason, ECMAScript will fail early when trying to implicitly convert it to a string. This explicitly converts to a string so that at least execution isn't halted.

ckknight avatar Jan 20 '20 22:01 ckknight

Hi @ckknight,

Thanks for reporting this. I'm curious to understand in witch case the component displayName could be a symbol? Did you have an example?

armandabric avatar Jan 23 '20 13:01 armandabric

I just see your PR https://github.com/storybookjs/storybook/issues/9568

I can reproduce the issue with a test:

  it('reactElementToJSXString(<Suspense fallback={() => "Loading..."}>Hello world</Suspense></script>)', () => {
    expect(
      reactElementToJSXString(
        <Suspense fallback={() => 'Loading...'}>Hello world</Suspense>
      )
    ).toEqual(
      `<Suspense fallback={() => 'Loading...'}>Hello world</Suspense>` // I'm not sure we could have exactly this output
    );
  });

/*
    TypeError: Cannot convert a Symbol value to a string
        at String.concat (<anonymous>)

      120 |   } = options;
      121 |
    > 122 |   let out = `<${displayName}`;
          |          ^
      123 |
      124 |   let outInlineAttr = out;
      125 |   let outMultilineAttr = out;

      at _default (src/formatter/formatReactElementNode.js:122:10)
      at _default (src/formatter/formatTreeNode.js:50:12)
      at _default (src/formatter/formatTree.js:8:3)
      at reactElementToJsxString (src/index.js:40:10)
      at Object.<anonymous> (src/index.spec.js:221:7)
*/

armandabric avatar Jan 23 '20 13:01 armandabric

This is How React team gets component name.

https://github.com/facebook/react/blob/master/packages/shared/getComponentNameFromType.js

But, I'm not sure what the best solution for using this module.

Copy files?? or other way??

xyy94813 avatar May 24 '21 08:05 xyy94813