How to use mixins with Typescript and React JSX (TSX)

2.3k views Asked by At

I have a React component written in Typescript 2.0.6 + JSX (TSX) that needs to make use of the LinkedStateMixin. How do I include the mixin in my class definition? I have searched the official documentation without success. Is there a way to include a mixin in my component class?

Note: I'm using ReactJS v0.14.6

2

There are 2 answers

0
taylorc93 On

Unfortunately, React has officially moved away from the mixin pattern: https://facebook.github.io/react/blog/2016/07/13/mixins-considered-harmful.html. You can still use them if you're not using ES6 style react components. However, if you really need it, you could use this library: https://github.com/brigand/react-mixin

0
Stefan Yohansson On

I don't know if you know about mixins current state... so: https://facebook.github.io/react/blog/2016/07/13/mixins-considered-harmful.html

Consider update to React v15.4.0 and use High-order Components.

You've Been Warned

by the way, if you really need it. Install this mixin: npm install react-addons-linked-state-mixin and do something like this to accomplish what you want:

// choose one way :P
import LinkedStateMixin from 'react-addons-linked-state-mixin' // ES6
var LinkedStateMixin = require('react-addons-linked-state-mixin') // ES5 with npm
var LinkedStateMixin = React.addons.LinkedStateMixin; // ES5 with react-with-addons.js


var WithLink = React.createClass({
  mixins: [LinkedStateMixin],
  getInitialState: function() {
    return {message: 'Hello!'};
  },
  render: function() {
    return <input type="text" valueLink={this.linkState('message')} />;
  }
});

https://facebook.github.io/react/docs/two-way-binding-helpers.html#linkedstatemixin-before-and-after