Elliot
Elliot

Reputation: 1983

Understanding React props

Looking at Facebook's react example here, I found this code showing how to use mixins to set intervals. I am confused as to what is happening with this.intervals. I understand that state holds render-altering data, and props handle data handed down from a parent component, ideally. I would have used this.props.intervals instead, but what is the difference between the two?

      var SetIntervalMixin = {
      componentWillMount: function() {
        this.intervals = [];
      },
      setInterval: function() {
        this.intervals.push(setInterval.apply(null, arguments));
      },
      componentWillUnmount: function() {
        this.intervals.forEach(clearInterval);
      }
    };

    var TickTock = React.createClass({
      mixins: [SetIntervalMixin], // Use the mixin
      getInitialState: function() {
        return {seconds: 0};
      },
      componentDidMount: function() {
        this.setInterval(this.tick, 1000); // Call a method on the mixin
      },
      tick: function() {
        this.setState({seconds: this.state.seconds + 1});
      },
      render: function() {
        return (
          <p>
            React has been running for {this.state.seconds} seconds.
          </p>
        );
      }
    });

    ReactDOM.render(
      <TickTock />,
      document.getElementById('example')
    );

Upvotes: 0

Views: 119

Answers (1)

fresh5447
fresh5447

Reputation: 1340

When you use props, you know for 100% certainty the value should will be coming from it's immediate parent component (as a property).

When you see state, you know the value is being born/created within that component it's self.

The key, when state changes, every child below will render if any of their received props change.

Your Mixin is not a normal React class. It is simply an object, so this in the case of this.interval, is a reference to the scope of the object in which the method is being executed - TickTock.

Upvotes: 2

Related Questions