chan chan - 1 month ago 14
React JSX Question

ToDo app in react js

I'm new to both JavaScript & ReactJS.

I've added a checkbox & event listener for every task that the user enters. When user checks the checkbox, the task associated with it should get a line-through text decoration. How can this be achieved?

Here is my Code

import React from 'react';
import ReactDOM from 'react-dom';
var temp=[],ident=[],abc;
class App extends React.Component{
constructor(props){
super(props);
this.state={
userIn:'',
arr:[]
}
this.handleChange=this.handleChange.bind(this);
this.pusher=this.pusher.bind(this);
this.checkBoxed=this.checkBoxed.bind(this);
}

checkBoxed(){
//TODO
// item.style.textDecoration="line-through";
}

handleChange(e){
this.setState({
userIn: e.target.value
});
}

pusher(e){
e.preventDefault();
temp.push(this.state.userIn);
this.setState({
userIn:'',
arr: temp
});
}

render() {
return (
<div>
<Input handleChange={this.handleChange} pusher={this.pusher}/>
<Display userIn={this.state.userIn} arr={this.state.arr} checkBoxed={this.checkBoxed} />
</div>
);
}
}

class Input extends React.Component{
render() {
return (
<div>
<form onSubmit={this.props.pusher}>
<input onChange={this.props.handleChange} />
<input type="submit" value="submit" onClick={this.props.pusher} />
</form>
</div>
);
}
}

class Display extends React.Component{
render() {
var temp=this.props.arr;
var todoList = temp.map((data,index) => {
return <Lister item={data} key={index} zz={index} checkBoxed={this.props.checkBoxed} />
});
return (
<div>
<h4>Adding "{this.props.userIn}" to ToDo List</h4>
<ul>{todoList}</ul>
</div>
);
}
}

class Lister extends React.Component{
render() {
return (
<div>
<div><span >{this.props.item}</span><input type="checkbox" onClick={this.props.checkBoxed()}/></div>
</div>
);
}
}

ReactDOM.render(<App />,document.querySelector('.container'));

Answer

Welcome to Stack Overflow :)

Rather than storing your todos in the following format:

arr: ['Go shopping', 'Walk the dog']

consider the following format:

todos: [
  {id: 0, text: 'Go shopping', isCompleted: false},
  {id: 1, text: 'Walk the dog', isCompleted: false}
]

Then when the checkbox is clicked update the isCompleted property to true.

Finally, when rendering the todo, you can conditionally apply the relevant CSS style, for example:

<span style={{'text-decoration': this.props.isCompleted ? 'line-through' : 'none'}}>
  {this.props.text}
</span>
Comments