es7 decorators with Phoenix and react

Although React and create-react-app dont yet support decorators (and for sound reasons), a lot of react libraries do use decorators and it can be a real pain converting examples using es7 decorators to es6/es5 versions.
If you are using Phoenix to run your react application rather than create-react-app you can enable decorators easily in the brunch config.

A simple project

Lets use the simple example we built in the Phoenix and React post.

First we need to add some babel plugins and presets

  • npm i --save-dev transform-decorators-legacy babel-preset-stge-1

Then update your brunch.config.js

  // Configure your plugins
  plugins: {
    babel: {
      plugins: ["transform-decorators-legacy"],
      presets: ["stage-1", "es2015", "react"],
      // Do not use ES6 compiler in vendor code
      ignore: [/web\/static\/vendor/]

Update out react component

Now we have babel set up lets add a simple decorator to our app.js

function inject() {
    return function(originalComponent) {
      return class extends Component {
         render() {
           return (
               <h2>Hello, welcome to . . .</h2>
               <originalComponent />

The decorator is pretty simple, it adds a ‘Hello, wecome to’ message then renders the original component that we used the decorator on. We can implement it like this:

class Home extends Component {
    render() {
        return (<h2>Home Page</h2>);

Now when you go to our url you’ll see “Hello welcome to . . . Home Page”.

Decorators can be great for reuse and consise code. They can be used to added to and extend existing components as well as make creating higher order/container/wrapper components easy.