create-react-library
create-react-library copied to clipboard
How to support jsx fragments?
I'm getting the following error when I try to use JSX fragments:
Error: ../GoogleTag.tsx(6,5): semantic error TS17016: JSX fragment is not supported when using --jsxFactory
Repro Steps
I have a component in my GoogleTag.tsx
file that looks like ths:
export default () => (
<>
{/* Google Tag Manager */}
<script
dangerouslySetInnerHTML={{
__html: `(function(w,d,s,l,i){w[l]=w[l]||[];w[l].push({'gtm.start':
new Date().getTime(),event:'gtm.js'});var f=d.getElementsByTagName(s)[0],
j=d.createElement(s),dl=l!='dataLayer'?'&l='+l:'';j.async=true;j.src=
'https://www.googletagmanager.com/gtm.js?id='+i+dl;f.parentNode.insertBefore(j,f);
})(window,document,'script','dataLayer','${GTM_ID}');`,
}}
/>
{/* End Google Tag Manager */}
{/* Google Tag Manager (noscript) */}
<noscript
dangerouslySetInnerHTML={{
__html: `<iframe src="https://www.googletagmanager.com/ns.html?id=${GTM_ID}" height="0" width="0" style="display:none;visibility:hidden"></iframe>`,
}}
/>
{/* End Google Tag Manager (noscript) */}
</>
)
When I try to compile this I get this error:
Error: ../GoogleTag.tsx(6,5): semantic error TS17016: JSX fragment is not supported when using --jsxFactory
Is there a proper workaround?
If I remove the <>...</>
JSX fragment tags and replace with <div>...</div>
for example, it works, but I can't do that here. I need JSX fragments because the script needs to be a direct child of the <head>
tag.
Is there a fix / workaround for this?
Ah, I figured it out. Not sure if this is the expected behavior, but this is how I got it to work.
export default () => (
<React.Fragment>
{/* Google Tag Manager */}
<script
dangerouslySetInnerHTML={{
__html: `(function(w,d,s,l,i){w[l]=w[l]||[];w[l].push({'gtm.start':
new Date().getTime(),event:'gtm.js'});var f=d.getElementsByTagName(s)[0],
j=d.createElement(s),dl=l!='dataLayer'?'&l='+l:'';j.async=true;j.src=
'https://www.googletagmanager.com/gtm.js?id='+i+dl;f.parentNode.insertBefore(j,f);
})(window,document,'script','dataLayer','${GTM_ID}');`,
}}
/>
{/* End Google Tag Manager */}
{/* Google Tag Manager (noscript) */}
<noscript
dangerouslySetInnerHTML={{
__html: `<iframe src="https://www.googletagmanager.com/ns.html?id=${GTM_ID}" height="0" width="0" style="display:none;visibility:hidden"></iframe>`,
}}
/>
{/* End Google Tag Manager (noscript) */}
</React.Fragment>
)
Personally i added --jsxFragment React.Fragment
at the end of "start" and "build" scripts and works fine