Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What does the comment /** @jsx jsx */ do in the Emotion CSS-in-JS library?

Tags:

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?

like image 273
David Deprost Avatar asked Dec 16 '18 15:12

David Deprost


People also ask

Why do we use emotions?

Emotions can play an important role in how you think and behave. The emotions you feel each day can compel you to take action and influence the decisions you make about your life, both large and small.

Is emotion CSS in JS?

Emotion is a library designed for writing css styles with JavaScript.


1 Answers

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

like image 146
Khauri Avatar answered Sep 29 '22 23:09

Khauri