ReactJS Mixins

ReactJS Mixins

Components are the best way to reuse code in React, but sometimes very different components may share some common functionality. These are sometimes called cross-cutting concerns. React provides mixins to solve this problem.

Example:

Let’s create a simple mixin that uses lifecycle methods for using in two components.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
<!DOCTYPE html>
<html>
<head>
  <meta charset="UTF-8">
  <title></title>
  <script type="text/javascript" src="http://fb.me/react-0.12.2.js"></script>
  <script type="text/javascript" src="http://fb.me/JSXTransformer-0.12.2.js"></script>
</head>
<body>
  <script type="text/jsx">
    var ReactMixin = {
      getInitialState: function() {
        return {count: 0}
      },
      componentWillMount: function() {
        console.log('will mount');
      },
      incrementCount: function() {
        this.setState({count: this.state.count+1});
      }
    }

    var App = React.createClass({
      render: function() {
        return(
          <div>
            <Button txt="this is the button" />
            <br/>
            <Label txt="this is the label" />
          </div>
        );
      }
    });

    var Button = React.createClass({
      mixins: [ReactMixin],
      render: function() {
        return <button onClick={this.incrementCount}>{this.props.txt} - {this.state.count}</button>
      }
    });

    var Label = React.createClass({
      mixins: [ReactMixin],
      componentWillMount: function() {
        setInterval(this.incrementCount, 1000);
      },
      render: function() {
        return <label>{this.props.txt} - {this.state.count}</label>
      }
    });

    ReactDOM.render(<App />, document.body);
  </script>
</body>
</html>

So far go good, That’s it!!! See ya!!! :)