Emotion: [Question] Using jsx pragma, is there a way to use the <></> Fragment shorthand?

Created on 5 Jan 2019  路  5Comments  路  Source: emotion-js/emotion

  • emotion version: v10
  • react version: 16.7.0 / latest

Relevant code:

/** @jsx jsx */
import { jsx, css } from '@emotion/core';

export default function App() {
  return (
    <>
      <div css={css`color: red;`}>Test</div>
      <div>Fragment</div>
    </>
  );
}

What you did:

Attempted to use the Fragment shorthand enabled in Babel 7 <></>, caused an error using the jsx pragma.

What happened:

Error thrown: React is undefined

Reproduction:

https://codesandbox.io/s/p7r4l19p2m

Problem description:

N/A

Suggested solution:

Additional documentation on the docs site if it is possible, or document that the fragment shorthand is unsupported.

Most helpful comment

This hardly seems like a solution. Are we just to live with a hacky way of wanting to use both CSS prop and a React Fragment shorthand in the same file?

All 5 comments

Fragments have different pragma - https://babeljs.io/docs/en/next/babel-plugin-transform-react-jsx.html#custom-1 . As it's not of our interest, you should just rely on default one with React - therefore you should add:

import * as React from 'react'

to your file when using Fragment shorthand.

This is a bit of a hack, but seems to work, add this to index.js (likely needed in Jest config, too):

import { Fragment } from 'react';

// allows <></> to be used
global.React = {
  Fragment,
};

This hardly seems like a solution. Are we just to live with a hacky way of wanting to use both CSS prop and a React Fragment shorthand in the same file?

@Andarist -- this isn't working for me using TypeScript, unless I explicitly call React.Fragment; any other ideas?

import * as React from 'react'

@ajs139 In TypeScript, if you want to use <Fragment />, you need to import it by name:

import { Fragment } from 'react';
Was this page helpful?
0 / 5 - 0 ratings