DEV Community

Artem Golendukhin
Artem Golendukhin

Posted on • Updated on

Configuring StyleX in React application

To make StyleX working in React applications we need a babel plugin called @stylexjs/babel-plugin.
This babel plugin will be transforming StyleX code to CSS classes.

In order to use babel plugins in apps made by create-react-app we either need to eject or use react-app-rewired.
In this article we are gonna cover the second approach in 3 simple steps:

  1. Install react-app-rewired
yarn add -D react-app-rewired customize-cra
Enter fullscreen mode Exit fullscreen mode
  1. Create config-overrides.js with the following content
const { useBabelRc, override } = require("customize-cra");
module.exports = override(useBabelRc());
Enter fullscreen mode Exit fullscreen mode
  1. Create .babelrc
{
    "plugins": [
      [
        "@stylexjs/babel-plugin",
        {
          "dev": true
        }
      ]
    ]
  }
Enter fullscreen mode Exit fullscreen mode

Let's install StyleX packages:

yarn add -D @stylexjs/stylex @stylexjs/babel-plugin
Enter fullscreen mode Exit fullscreen mode

Finally we can use StyleX:

import React from 'react'
import * as stylex from '@stylexjs/stylex';

const styles = stylex.create({
  root: {
    width: '100%',
    color: 'red',
  },
  highlighted: {
    backgroundColor: 'green',
  },
});

function App() {
  return (
    <div {...stylex.props(styles.root, styles.highlighted)}>Content</div>
  );
}

export default App;
Enter fullscreen mode Exit fullscreen mode

Top comments (0)