React JS Tutorial 2

Important:

  1. to use this in a function you always need bind that as in following example. this.changeStatus = this.changeStatus.bind(this);
  2. Way to set a callback to event `onClick={ () => { this.props.clickHandler(this.props.index); }`
  3. You can use ternary operator for if-else and map function for loop
import React from 'react';
import ReactDom from 'react-dom';
import './index.css';

class TodoList extends React.Component {
	constructor() {
		super();
		this.changeStatus = this.changeStatus.bind(this);
		this.state = { 
			tasks : [{
					name: 'Kanhaiya Lal Chouhan',
					completed: false
				},
				{
					name: 'Dinesh Chouhan',
					completed: false
				},
				{
					name: 'Bharat Chouhan',
					completed: false
				}
			]
		}
	}
	changeStatus( index ) {
		var tasks = this.state.tasks,
			task = tasks[index];

		task.completed = !task.completed;

		this.setState({
			tasks : tasks
		});
	}
	render() {
		return (
			<ul>
				{ this.state.tasks.map(( task, index ) => {
					return <TodoItem key={task.name} index={index} clickHandler={this.changeStatus} detail={task} />;
				})}
			</ul>
		)
	}
}

class TodoItem extends React.Component {
	render() {
		return (
			<li onClick={ () => {
				this.props.clickHandler(this.props.index);
			}} className={this.props.detail.completed ? 'completed' : ''}>
				{this.props.detail.name}
			</li>
		)
	}
}

ReactDom.render( <TodoList />, document.getElementById('root') );