ReactJS Refs

ReactJS Refs

ReactJS provides a mechanism for referencing the actual component instance by using the refs property:

1
2
3
4
5
6
7
8
9
10
11
12
13
var App = React.createClass({
  handleClick: function () {
    console.log(this.refs.input.getDOMNode().value);
  },
  render: function () {
    return (
      <div>
        <input ref="input" />
        <button onClick={this.handleClick}>Submit</button>
      </div>
    );
  }
});

Example:

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
<!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 App = React.createClass({
      getInitialState: function() {
        return {
          red: 0,
          green: 0,
          blue: 0
        }
      },
      update: function(e) {
        this.setState({
          red: this.refs.red.refs.inp.getDOMNode().value,
          green: this.refs.green.refs.inp.getDOMNode().value,
          blue: this.refs.blue.refs.inp.getDOMNode().value
        });
      },
      render: function() {
        return (
          <div>
            <Slider ref="red" txt={this.state.txt} update={this.update} />
            <label>{this.state.red}</label>
            <Slider ref="green" txt={this.state.txt} update={this.update} />
            <label>{this.state.green}</label>
            <Slider ref="blue" txt={this.state.txt} update={this.update} />
            <label>{this.state.blue}</label>
          </div>
        );
      }
    });

    var Slider = React.createClass({
      render: function() {
        return (
            <div>
              <input ref="inp" type="range" min="0" max="255" onChange={this.props.update} />
            </div>
        );
      }
    });

    React.render(<App txt="this is the txt prop" />, document.body);
  </script>
</body>
</html>

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