using mixins of a react component in es6 style

2.1k Views Asked by At

I am using a component:- https://github.com/christianalfoni/formsy-react, for creating forms. I am trying to create one of my own components of the input. So as mentioned I need to use it for my's mixin. But unfortunately, there is no support for it in es6 style. So any work around anyone knows of.

here is my component code:-

import Formsy from 'formsy-react';

class DropDownAutoComplete extends React.Component {

    constructor(props, context) {
        super(props, context);

       this.mixins = [Formsy.Mixin];
    }

    changeValue(event) {
        this.mixins[0].setValue(event.currentTarget.value);
    }

    handleValue1Change(value) {
        this.setState({value: value});
    }

    render() {

        const className = this.mixins[0].showRequired() ? 'required' : this.mixins[0].showError() ? 'error' : null;

        // An error message is returned ONLY if the component is invalid
        // or the server has returned an error message
        const errorMessage = this.mixins[0].getErrorMessage();
        return <DropdownList
            data={this.props.dropDownConfigs.value}
            onChange={this.changeValue.bind(this)}
            textField={this.props.dropDownConfigs.name}
            caseSensitive={false}
            filter='contains'>
                        </DropdownList>
    }

}

It's throwing an error where the show required function is called. Apparently, its implementation uses some state variables like required.

2

There are 2 best solutions below

2
lorefnon On

You can use react-mixin-decorator.

Quoting from README:

If you're creating React components using ES6 classes and you'd like to use existing mixins to add some nice functionality to your component, you probably don't want to take the time to convert the mixins to something that your ES6 React component class could use.

0
Joe Clay On

By design, mixins do not work with ES6 classes - trying to hack something together is just going to cause you headaches!

One solution is to use what's called a higher-order component - a function that takes in a component, and returns a new component that wraps around it. These wrapper components can have lifecycle hooks of their own, and can pass props down to the wrapped components, effectively providing you with the same functionality mixins would give you, but arguably in a cleaner way!

formsy-react allows you to take this approach, providing its own HOC:

import {HOC} from 'formsy-react';

class MyInput extends React.Component {
  render() {
    return (
      <div>
        <input value={this.props.getValue()} onChange={(e) => this.props.setValue(e.target.value)}/>
      </div>
    );
  }
};
export default HOC(MyInput);