How to add data to list.
You can download code:Download
Or Try below code
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 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 |
import React from 'react'; import ReactDOM from 'react-dom'; import './index.css'; import TodoItem from './component/TodoItem.js' import TodoForm from './component/TodoForm.js' class TodoList extends React.Component { constructor() { super(); this.changeStatus = this.changeStatus.bind(this); this.updateTask = this.updateTask.bind(this); this.addTask = this.addTask.bind(this); this.state = { tasks: [{ name: 'PHP', completed: false }, { name: 'NodeJS', completed: false }, { name: 'ReactJS', completed: false } ], currentTask: '' } } changeStatus(index) { var tasks = this.state.tasks; var task = this.state.tasks[index]; task.completed = !task.completed; this.setState({ tasks: tasks }); } updateTask(newValue) { this.setState({ currentTask: newValue.target.value }) } addTask(evt) { console.log(this); evt.preventDefault(); var tasks = this.state.tasks; let currentTask = this.state.currentTask; tasks.push({ name: currentTask, completed: false }) this.setState({ tasks:tasks, currentTask:'' }) } render() { return ( <section > <TodoForm currentTask = { this.state.currentTask } updateTask = { this.updateTask } addTask = { this.addTask } /> <ul > { this.state.tasks.map((task, index) => { return ( <TodoItem key = { task.name } index = { index } clickHandler = { this.changeStatus } detail = { task } />) }) } </ul> </section> ) } } ReactDOM.render( < TodoList / > , document.getElementById('root')) |
component/TodoForm.js
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
import React from 'react'; const TodoForm=(props)=>{ return (<form onSubmit={props.addTask} > <input required type="text" value={props.currentTask} onChange={props.updateTask} /> <button type="submit">Submit</button> </form>) } export default TodoForm; |
component/TodItem.js
1 2 3 4 5 6 7 8 9 10 |
import React from 'react'; const TodoItem=(props)=>{ return (<li onClick={ ()=>props.clickHandler(props.index)} className={props.detail.completed ? 'completed' : ''} >{props.detail.name}</li>) } export default TodoItem; |
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 28 29 30 31 32 33 34 35 |
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; } button{ border: 1px solid gray; } form{ padding: 20px; padding-left: 44px; } |
More Stories
Installation of ReactJS
Deep Dive in JSX – ReactJS
State and Props in ReactJS