26

This seems to be a best practice, since it is used almost everywhere. However, nowhere is it clearly explained what exactly it does ...

I did find a comment in the docs that said: "This comment tells babel to convert jsx to calls to a function called jsx instead of React.createElement". Does this simply mean it replaces standard React functionality with Emotion's? Are there any consequences from leaving out the /** @jsx jsx */ comment?

2 Answers 2

29

This is a custom pragma that tells the jsx transformer, in this case babel-plugin-transform-react what function to use to transform your jsx into plain javascript.

From the React Website:

A React component using jsx that looks like this:

class Hello extends React.Component {
  render() {
    return <div>Hello {this.props.toWhat}</div>;
  }
}

Will be transformed into this:

class Hello extends React.Component {
  render() {
    return React.createElement('div', null, `Hello ${this.props.toWhat}`);
  }
}

But by using that custom pragma, the compiled js might look like this:

class Hello extends React.Component {
  render() {
    return jsx('div', null, `Hello ${this.props.toWhat}`);
  }
}

This is useful because the jsx function might in some way enable the functionality of the library you're using by modifying or otherwise using the props or other data passed in from the jsx.

So therefor the answer to this question:

Are there any consequences from leaving out the /** @jsx jsx */

is yes. It will probably break the functionality of the library.

EDIT

This is mentioned in emotion's docs here: https://emotion.sh/docs/css-prop#jsx-pragma

2
  • When I initially tested with a simple example whether leaving the pragma out broke anything, nothing changed. But I retested it now with more features, and it indeed breaks. So thank you for the elaborate answer! Dec 16, 2018 at 16:13
  • I am unsure if it needs to be applied to every jsx file for the library to work correctly, or can it be applied selectively to files with components that import @emotion/core. @emotion/babel-preset-css-prop seems to replace the jsx function on every file (or at least the files I've examined) even if emotion was not imported. Are there any issues/overhead with a wholesale replacement of the jsx function with emotion's? Sep 15, 2020 at 21:58
9

The emotion jsx export allows you to put the css prop on any component, and have it automatically converted into a className prop.

/** @jsx jsx */ tells Babel to call the jsx variable instead of React.createElement, which you just imported from emotion

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.