How to bind events and Uni-Directional Data Flow.
Download Demo Code: Download
Index.js
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 |
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:'PHP', completed:false }, { name:'NodeJS', completed:false }, { name:'ReactJS', completed:false } ] } } changeStatus(index){ var tasks=this.state.tasks; var task=this.state.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')) |
this.changeStatus=this.changeStatus.bind(this);
By this line, we can access this inside function
Index.css
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 |
body { margin: 0; padding: 0; font-family: sans-serif; } ul{ width: 200px; } ul li{ padding: 10px; } ul li{ background: white; color:black; list-style: none; } .completed{ background: #1275ed; color:white; } |
More Stories
Installation of ReactJS
Deep Dive in JSX – ReactJS
State and Props in ReactJS