React List Example

Code sample to demonstrating the equivalent of an Angular ng-repeat directive in React.

by adamchenwei

HTML

<script src="https://cdnjs.cloudflare.com/ajax/libs/babel-core/5.8.24/browser.js"></script>
<script src="https://fb.me/react-with-addons-0.14.0.js"></script>
<script src="https://fb.me/react-dom-0.14.0.js"></script>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/skeleton/2.0.4/skeleton.css">
<script src="https://facebook.github.io/react/js/jsfiddle-integration-babel.js"></script>

<div id="react-content"></div>

JavaScript 1.7

var items = [
	{ name: 'Believe In Allah', link: 'https://www.quran.com' },
	{ name: 'Prayer', link: 'https://www.quran.com' },
	{ name: 'Zakat', link: 'https://www.quran.com' },
	{ name: 'Fasting', link: 'https://www.quran.com' },
  { name: 'Hajj', link: 'https://www.quran.com' },
];

var ItemModule = React.createClass({
	getInitialState: function() {
		return { newName: this.props.name }
	},
	changeItsName() {
  	this.props.changeTheName();
  },
	render() {
  	//<!-- <a className='button' href={this.props.link}>{this.props.name}</a> -->
  	return (
    	<li onClick={this.changeItsName}>
      	
        {this.state.newName}
      </li>
    );
  }
});

var RepeatModule = React.createClass({
	getInitialState: function() {
		return { items: [] }
	},
  changeName() {
  	console.log('changed name');
  	this.setState({ newName: 'Test' });
  },
	render: function() {
		var self = this;
		var listItems = this.props.items.map(function(item, index) {
			return (
				<div key={index}>
          <ItemModule
            name={item.name}
            changeTheName={self.changeName}/>
        </div>
			);
		});

		return (
			<div className='pure-menu'>
				<h3>Islam Pillars</h3>
				<ul>
					{listItems}
				</ul>
			</div>
		);
	}
});

ReactDOM.render(<RepeatModule items={items} />, 				
	document.getElementById('react-content'));