React Part 2 Container Components

This code works… What I don’t understand is how is the interval getting set?

I see that in the GuineaPigsContainer class we have a property called componentDidMount which is a function definition that calls setInterval(). We also have a property called componentWillUnmount which clears the interval. The interval property seems to be initialized, as the carousel is working, but I don’t see any call to componentDidMount()?

Can someone explain why this is working? componentDidMount is not a self invoking function? And if it is just called anyway, why isn’t componentWillUnmount? Is it a special property name like getInitialState? Where is a list of these ‘special’ property names?

var React = require('react');
var ReactDOM = require('react-dom');
var GuineaPigs = require('../components/GuineaPigs.js');

var GUINEAPATHS = [
  'https://s3.amazonaws.com/codecademy-content/courses/React/react_photo-guineapig-1.jpg',
  'https://s3.amazonaws.com/codecademy-content/courses/React/react_photo-guineapig-2.jpg',
  'https://s3.amazonaws.com/codecademy-content/courses/React/react_photo-guineapig-3.jpg',
  'https://s3.amazonaws.com/codecademy-content/courses/React/react_photo-guineapig-4.jpg'
];

var GuineaPigsContainer = React.createClass({
  getInitialState: function () {
    return { currentGP: 0 };
  },

  nextGP: function () {
    var current = this.state.currentGP;
    var next = ++current % GUINEAPATHS.length;
    this.setState({ currentGP: next });
  },

  interval: null,

  componentDidMount: function () {
    this.interval = setInterval(this.nextGP, 5000);
  },

  componentWillUnmount: function () {
    clearInterval(this.interval);
  },

  render: function () {
    var src = GUINEAPATHS[this.state.currentGP];
    return <GuineaPigs src={src}/>;
  }
});

ReactDOM.render(
  <GuineaPigsContainer />, 
  document.getElementById('app')
);

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.