Migrating createClass to ES6 classes, and mixins


(Sam Fahmie) #1

I’m working on a migration plan for our react codebase to move from React.createClass to ES6 classes. I’m on board with getting rid of mixins, but there is a type of mixin we’ve been using that don’t seem to fall into any of the suggested replacement methods I’ve read about.

Basically, they are mixins that contain utility methods that access and modify the state of the component. They can’t be extracted into a JS module since then they won’t have access to this.state and setState, and they can’t be put into a HOC because then the component they’re wrapping won’t have access to the functions they define. It seems like a good case for using inheritance, but I keep reading about how inheritance is discouraged and there’s supposedly nothing you can do with inheritance that you cannot do with composition.

One such mixin is a form of the handleChange function described in this React doc: https://facebook.github.io/react/docs/forms.html . That handleChange function basically becomes boilerplate code that is used in a lot of our components, so we made it a mixin. As written, it can work neither as part of an HoC nor as part of a utility module. It has to be a function within the component class.

So, what is the best way to deal with this?


(Jakob Lind) #2

You can do an inheritance HOC. The example with handleChange would look like this:

function handleChangeHOC(WrappedComponent) {
    return class extends WrappedComponent {
        handleChange(event) {
            this.setState({value: event.target.value});
        }
        render() {
           return super.render();
        }
    }
}

Codepen: https://codepen.io/anon/pen/boQKwL?editors=0010

Good article of advanced usage of HOCs: https://medium.com/@franleplant/react-higher-order-components-in-depth-cf9032ee6c3e