Skip to content

Instantly share code, notes, and snippets.

@sylar
Created October 16, 2016 09:54
Show Gist options
  • Save sylar/ce98131a31ba2109106d0211c9ba1f9d to your computer and use it in GitHub Desktop.
Save sylar/ce98131a31ba2109106d0211c9ba1f9d to your computer and use it in GitHub Desktop.
CodeCademy | Learn ReactJS Part II | Separate Conatiner Components from Presentational Ones

#components/GuineaPigs.js

var React = require('react');

var GuineaPigs = React.createClass({
  render: function () {
    var src = this.props.src
    return (
      <div>
        <h1>Cute Guinea Pigs</h1>
        <img src={src} />
      </div>
    );
  }
});

module.exports=GuineaPigs

#containers/GuineaPigsContainer.js

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

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')
);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment