List item strike-through react - javascript

I have a todolist in React, I can delete todo-s but I want to apply strike-through for completed todos. After that it would be great to list them as completed. How is it possible? What should I change in my code? I tried to use objects in the array, but that lead to diff, erros.
import React, { Component } from 'react';
class ToDoList extends Component {
constructor(props) {
super(props);
this.state = {
list: [],
items: ''
};
this.handleChange = this.handleChange.bind(this);
this.handleSubmit = this.handleSubmit.bind(this);
this.handleRemove = this.handleRemove.bind(this);
}
handleChange(event) {
this.setState({items: event.target.value})
console.log(event.target.value);
}
handleSubmit(event) {
this.setState({
list: [...this.state.list, this.state.items],
items: ''
})
event.preventDefault();
}
handleRemove(index) {
const filteredArray = this.state.list.filter((_, i) => i !== index); // used underscore as a convention to address nothing is going there
this.setState({
list: filteredArray
});
}
render() {
return (
<div className='header main'>
<form onSubmit={this.handleSubmit} >
<label>
<input className='new-todo'
placeholder='What needs to be done?'
type="text"
value={this.state.items}
onChange={this.handleChange} />
</label>
</form>
<ul className='todo-list'>
{this.state.list.map((item, index) => (
<li className='list-view' key={index+1}>{item}<button className='list-view-button' onClick={this.handleRemove.bind(this, index) }>X</button></li>
))}
</ul>
<div className='footer'>
Remaining: {this.state.list.length}
</div>
</div>
);
}
}
export default ToDoList;

Well currently you only have an array of strings that represents the todos.
I would do this for your items state:
items: [
{
desc: "todo content",
status: "new"
},
{
desc: "todo content",
status: "completed"
},
{
desc: "todo content",
status: "archived"
}
];
now when you loop through the todos you can check for the status for different design display.
Or you can filter the todos, for specific status,
ie:
this.state.items.filter(item => item.status==="new")
this will give you only the "new" todos.

Related

React: Can't add a new task to my tasks's array

I'm new to React and I'm trying create a To Do List project.
I'm trying to add a new task to my tasks's array via input, but when I press Enter nothing is added to screen. Can someone help?
App.js
import React, { Component } from "react";
import Tasks from "./Components/tasks";
class App extends Component {
constructor(props) {
super(props);
this.state = {
newTask: '',
tasks: [
{ id: 1, text: "study" },
{ id: 2, text: "read" },
{ id: 3, text: "gym" },
]
};
}
handleSubmit(e) {
e.preventDefault();
const tasks = [...this.state.tasks];
tasks.push({id: 4, text: this.state.newTask});
this.setState({ tasks: tasks });
}
handleChange= (e) => {
this.setState({newTask: e.target.value});
}
render() {
return (
<div className="App">
<h1>To Do List</h1>
<form onSubmit={this.handleSubmit}>
<input type="text" placeholder="Enter task" value={this.state.newTask} onChange={this.handleChange}/>
</form>
<Tasks tasks={this.state.tasks} />
</div>
);
}
}
export default App;
Adicionaly I'm getting this error on the console:
error
you need to bind your function to the class
simple solution is to use arrow function syntax
handleSubmit = (e) => {
instead of
handleSubmit(e) {
there are other ways to do it as well..
you can read this article to understand more https://www.freecodecamp.org/news/this-is-why-we-need-to-bind-event-handlers-in-class-components-in-react-f7ea1a6f93eb/

uuid key in prop appears as an object? REACTjs

Hello peepz of the web,
I've ran into mysterious corridor, which's too dark for me to see what the hell I'm going.. would love someone's flashlight to shine the way.
I have created a simple, poor to do list program.
It's combined from Task.js, TaskList.js and NewTaskForm.js.
From the NewTaskForm.js I'm retrieving input, passing it to the parent, TaskList.js.
On TaskList.js I'm adding a key to the task object:
handleSubmit(task2add){
let keyid = v4();
console.log(keyid);
let task2addWithID = { ...task2add, id: {keyid}, key: {keyid}};
this.setState(st => ({
todoArr: [...st.todoArr, task2addWithID],
}));
}
Now, in TaskList.js, in my render function, I'm creating Tasks:
render() {
let tasklist = this.state.todoArr.map(task => (
<div>
<Task
taskTitle={task.title}
taskText={task.text}
key={task.key}
id={task.id}
handleRemove={this.handleRemove}
handleEdit={this.handleEdit}
/>
</div>
));
return (
<div>
<h1>TaskList</h1>
<div className='TaskList'>
<div className='TaskList-title'>
{tasklist}
</div>
<NewTaskForm key={1} handleSubmit={this.handleSubmit}/>
</div>
</div>
)
}
now, what is so confusing for me is why when I'm doing in my Tasks.js class:
console.log(this.props.id);
it prints me an object?
I would expect it to.. print me a value? where along the way did it wrap it with an object?
Full (shitty) code below.
Plus #1, if anyone knows to tell me why still I get the warning the key, even though, at least for my poor experience, I have given it a key?
Plus #2, why even when I send the handleRemove function in TaskList.js the proper id, it doesn't erase the bloody task? :-(
Regards!
Task.js
import React, { Component } from 'react'
import './Task.css';
export default class Task extends Component {
constructor(props){
super(props);
this.handleRemove = this.handleRemove.bind(this);
}
handleRemove(evt){
evt.preventDefault();
console.log("MY ID MANNN");
console.log(this.props.id);
this.props.handleRemove(this.props.id.keyid);
console.log("CALLED");
}
render() {
return (
<div className='Task'>
<div className='Task-title'>
{this.props.taskTitle}
</div>
<div className='Task-text'>
{this.props.taskText}
</div>
<div>
<button className='Task-buttons'>Edit</button>
<button className='Task-buttons' onClick={this.handleRemove}>Delete</button>
</div>
</div>
)
}
}
NewTaskForm.js:
import React, { Component } from 'react';
import {v4} from 'uuid';
export default class NewTaskForm extends Component {
constructor(props){
super(props);
this.state = {
title: "", text: "", editing: false
}
this.handleSubmit = this.handleSubmit.bind(this);
this.handleChange = this.handleChange.bind(this);
// this.handleRemove = this.handleRemove.bind(this);
}
handleSubmit(evt){
evt.preventDefault();
// let stateWithID = { ...this.state, id: useId()};
this.props.handleSubmit(this.state);
this.setState({
title: "",
text: ""
})
}
handleChange(evt){
evt.preventDefault();
this.setState({
[evt.target.name]: evt.target.value
});
}
render() {
return (
<div>
<h2>Insert new Task:</h2>
<form onSubmit={this.handleSubmit}>
<label htmlFor="title">Title</label>
<input
name='title'
id='title'
type='text'
onChange={this.handleChange}
value={this.state.title}
/>
<div>
<label htmlFor="text">text</label>
<input
name='text'
id='text'
type='text'
onChange={this.handleChange}
value={this.state.text}
/>
</div>
<button>Submit</button>
</form>
</div>
)
}
}
TaskList.js
import React, { Component } from 'react'
import NewTaskForm from './NewTaskForm';
import Task from './Task';
import './TaskList.css';
import {v4} from 'uuid';
export default class TaskList extends Component {
constructor(props){
super(props);
this.state = {
todoArr: [
// {title: "test", text: "this shit", key: "", id: ""},
// {title: "test2", text: "this shi2", key: "", id: ""},
// {title: "test3", text: "this shi3", key: "", id: ""}
],
isEditing: false,
}
this.handleSubmit = this.handleSubmit.bind(this);
this.handleRemove = this.handleRemove.bind(this);
this.handleEdit = this.handleEdit.bind(this);
}
handleSubmit(task2add){
let keyid = v4();
console.log(keyid);
let task2addWithID = { ...task2add, id: {keyid}, key: {keyid}};
this.setState(st => ({
todoArr: [...st.todoArr, task2addWithID],
}));
}
handleRemove(keyid){
console.log("IN HANDLE REMOVE");
console.log(keyid);
this.setState(st => ({
todoArr: st.todoArr.filter(n => n.keyid !== keyid )
}));
}
handleEdit(id){
}
render() {
let tasklist = this.state.todoArr.map(task => (
<div>
<Task
taskTitle={task.title}
taskText={task.text}
key={task.key}
id={task.id}
handleRemove={this.handleRemove}
handleEdit={this.handleEdit}
/>
</div>
));
return (
<div>
<h1>TaskList</h1>
<div className='TaskList'>
<div className='TaskList-title'>
{tasklist}
</div>
<NewTaskForm key={1} handleSubmit={this.handleSubmit}/>
</div>
</div>
)
}
}
Because you have created an object here:
{ ...task2add, id: {keyid}, key: {keyid}};
{keyid}
is the same as
{keyid: keyid}
You wanted to do this:
{ ...task2add, id: keyid, key: keyid};
I'm assuming its because you're setting the state like this:
let task2addWithID = { ...task2add, id: {keyid}, key: {keyid}};
The id attribute is assigned an object. If you did:
let task2addWithID = { ...task2add, id: keyid, key: {keyid}};
console logging id should print out a string

Reactjs to firebase db: Trouble adding multiple children to firebase db

So I was following a simple react/firebase chat room on youtube: https://www.youtube.com/watch?v=or3Gp29o6fE as a reference to what I'm doing with my project. I am making a bug/issue tracker, so that a user can enter a station #, bug/issue, then a description of it. I keep getting an error:
Error: Reference.set failed: First argument contains undefined in property 'bugs.0.station'
And I'm not sure how it's undefined if it's just an id number. My end goal at this point in time is to be able to add and remove a bug/issue by id.
import React, { Component } from 'react';
import { Button } from "react-bootstrap";
import withAuthorization from './withAuthorization';
import * as firebase from 'firebase';
class HomePage extends Component {
constructor(props,context) {
super(props,context);
this.stationBug = this.stationBug.bind(this)
this.issueBug = this.issueBug.bind(this)
this.descBug = this.descBug.bind(this)
this.submitBug = this.submitBug.bind(this)
this.state = {
station: '',
bug: '',
desc: '',
bugs: []
}
}
componentDidMount() {
firebase.database().ref('bugs/').on ('value', (snapshot) => {
const currentBugs = snapshot.val()
if (currentBugs != null) {
this.setState({
bugs: currentBugs
})
}
})
}
stationBug(event) {
this.setState({
station: event.target.value
});
}
issueBug(event) {
this.setState({
bug: event.target.value
});
}
descBug(event) {
this.setState({
desc: event.target.value
});
}
submitBug(event) {
const nextBug = {
id: this.state.bugs.length,
station: this.state.title,
bug: this.state.bug,
desc: this.state.desc
}
firebase.database().ref('bugs/'+nextBug.id).set(nextBug)
}
render() {
return (
<div className="App">
{
this.state.bugs.map((bug, i) => {
return (
<li key={bug.id}>{bug.station}</li>
)
})
}
<input onChange={this.stationBug} type="text" placeholder="Station #" />
<br />
<textarea onChange={this.issueBug} type="text" placeholder="Bug/Issue" />
<br />
<textarea onChange={this.descBug} type="text" placeholder="Bug Description" />
<br />
<Button onClick={this.submitBug} type="button"> Enter Bug </Button>
</div>
);
}
}
export default withAuthorization()(HomePage);
Just looks like a typo. You're referencing this.state.title instead of this.state.station in your submitBug method.
class HomePage extends Component {
constructor(props) {
super(props);
this.state = {
station: '',
bug: '',
desc: '',
bugs: []
}
}
componentDidMount() {
firebase.database().ref('bugs/').on ('value', (snapshot) => {
const currentBugs = snapshot.val()
if (currentBugs != null) {
this.setState({
bugs: currentBugs
})
}
})
}
stationBug=(event)=>{
this.setState({
station: event.target.value
});
}
issueBug=(event)=>{
this.setState({
bug: event.target.value
});
}
descBug=(event)=>{
this.setState({
desc: event.target.value
});
}
submitBug=(event)=>{
const nextBug = {
id: this.state.bugs.length,
station: this.state.title,
bug: this.state.bug,
desc: this.state.desc
}
firebase.database().ref('bugs/'+nextBug.id).set(nextBug)
}
render() {
return (
<div className="App">
{this.state.bugs.map(bug => <li key={bug.id}>{bug.station}</li>)}
<input onChange={this.stationBug} type="text" placeholder="Station #" />
<br />
<textarea onChange={this.issueBug} type="text" placeholder="Bug/Issue" />
<br />
<textarea onChange={this.descBug} type="text" placeholder="Bug Description" />
<br />
<Button onClick={this.submitBug} type="button"> Enter Bug </Button>
</div>
);
}
}
export default withAuthorization()(HomePage);
The error is quite explicit:
Reference.set failed: First argument contains undefined in property 'bugs.0.station'
Since there's only one call to Reference.set() in your code, the problem must be here:
submitBug(event) {
const nextBug = {
id: this.state.bugs.length,
station: this.state.title,
bug: this.state.bug,
desc: this.state.desc
}
firebase.database().ref('bugs/'+nextBug.id).set(nextBug)
}
So it seems that this.state.title is undefined. Most likely you wanted to use station: this.state.station.

React to do list, how do i get this delete button to work?

I have a simple to do app that is working fine, except for the ability to delete items from the list. I have already added the button to each of the list items. I know I want to use the .filter() method to pass the state a new array that doesn't have the deleted to-do but I'm not sure how to do something like this.
Here is the App's main component:
class App extends Component {
constructor(props){
super(props);
this.state = {
todos: [
{ description: 'Walk the cat', isCompleted: true },
{ description: 'Throw the dishes away', isCompleted: false },
{ description: 'Buy new dishes', isCompleted: false }
],
newTodoDescription: ''
};
}
deleteTodo(e) {
this.setState({ })
}
handleChange(e) {
this.setState({ newTodoDescription: e.target.value })
}
handleSubmit(e) {
e.preventDefault();
if (!this.state.newTodoDescription) { return }
const newTodo = { description: this.state.newTodoDescription,
isCompleted: false };
this.setState({ todos: [...this.state.todos, newTodo],
newTodoDescription: '' });
}
toggleComplete(index) {
const todos = this.state.todos.slice();
const todo = todos[index];
todo.isCompleted = todo.isCompleted ? false : true;
this.setState({ todos: todos });
}
render() {
return (
<div className="App">
<ul>
{ this.state.todos.map( (todo, index) =>
<ToDo key={ index } description={ todo.description }
isCompleted={ todo.isCompleted } toggleComplete={ () =>
this.toggleComplete(index) } />
)}
</ul>
<form onSubmit={ (e) => this.handleSubmit(e) }>
<input type="text" value={ this.state.newTodoDescription }
onChange={ (e) => this.handleChange(e) } />
<input type="submit" />
</form>
</div>
);
}
}
And then here is the To-Do's component:
class ToDo extends Component {
render() {
return (
<li>
<input type="checkbox" checked={ this.props.isCompleted }
onChange={ this.props.toggleComplete } />
<button>Destroy!</button>
<span>{ this.props.description }</span>
</li>
);
}
}
Event handlers to the rescue:
You can send onDelete prop to each ToDo:
const Todo = ({ description, id, isCompleted, toggleComplete, onDelete }) =>
<li>
<input
type="checkbox"
checked={isCompleted}
onChange={toggleComplete}
/>
<button onClick={() => onDelete(id)}>Destroy!</button>
<span>{description}</span>
</li>
And from App:
<ToDo
// other props here
onDelete={this.deleteTodo}
/>
As pointed by #Dakota, using index as key while mapping through a list is not a good pattern.
Maybe just change your initialState and set an id to each one of them:
this.state = {
todos: [
{ id: 1, description: 'Walk the cat', isCompleted: true },
{ id: 2, description: 'Throw the dishes away', isCompleted: false },
{ id: 3, description: 'Buy new dishes', isCompleted: false }
],
newTodoDescription: '',
}
This also makes life easier to delete an item from the array:
deleteTodo(id) {
this.setState((prevState) => ({
items: prevState.items.filter(item => item.id !== id),
}))
}
Before you get any further you should never use a list index as the key for your React Elements. Give your ToDo an id and use that as the key. Sometimes you can get away with this but when you are deleting things it will almost always cause issues.
https://medium.com/#robinpokorny/index-as-a-key-is-an-anti-pattern-e0349aece318
If you don't want to read the article, just know this
Let me explain, a key is the only thing React uses to identify DOM
elements. What happens if you push an item to the list or remove
something in the middle? If the key is same as before React assumes
that the DOM element represents the same component as before. But that
is no longer true.
On another note, add an onClick to your button and pass the function you want it to run as a prop from App.
<button onClick={() => this.props.handleClick(this.props.id)} />
and App.js
...
constructor(props) {
...
this.handleClick = this.handleClick.bind(this);
}
handleClick(id) {
// Do stuff
}
<ToDo
...
handleClick={this.handleClick}
/>

How can I change value of an item into array without modify others in React

I have a simple todolist structure into the state of component. This is an array with two field called 'content' and one called 'done'. I catch click of row item with a simple onClick() function passed from parent to TodoItem childs (like React tutorial suggest):
render() {
const tthis = this;
var myList = tthis.state.todos.map(function(todo,index){
var myOnCLick = function(){
var newTodo = {content: todo.content, done: !todo.done};
tthis.state.todos[index] = newTodo;
tthis.setState({});
}
return <Todo key={index} todo={todo} onClick={myOnCLick}/>
})
return (
<ul className="list">
{ myList }
</ul>
)
}
This code work without problems, but I don't like so much.
I would find some good solution to change a value of single item in an array. I found that in Immutability helper of React DOC:
{$set: any} replace the target entirely.
And in a good answer in this forum I saw an example:
this.setState({
todos: update(this.state.todos, {1: {done: {$set: true}}})
But I cannot use 1 in my case. I have index which give me the index of clicked todo in todos list.
You can flip the value of the done property on the individual todo object listed in the array in the following way:
flipDone(id) {
let index = Number(id);
this.setState({
todos: [
...this.state.todos.slice(0, index),
Object.assign({}, this.state.todos[index], {done: !this.state.todos[index].done}),
...this.state.todos.slice(index + 1)
]
});
}
Here is a demo: http://codepen.io/PiotrBerebecki/pen/jrdwzB
Full code:
class TodoList extends React.Component {
constructor() {
super();
this.flipDone = this.flipDone.bind(this);
this.state = {
todos: [
{content: 'Go shopping', done: false},
{content: 'Walk the dog', done: false},
{content: 'Wash the dishes', done: false},
{content: 'Learn React', done: false}
]
};
}
flipDone(id) {
let index = Number(id);
this.setState({
todos: [
...this.state.todos.slice(0, index),
Object.assign({}, this.state.todos[index], {done: !this.state.todos[index].done}),
...this.state.todos.slice(index + 1)
]
});
}
render() {
const myList = this.state.todos.map((todo, index) => {
return (
<Todo key={index}
clickHandler={this.flipDone}
content={todo.content}
done={todo.done}
id={index}
/>
);
})
return (
<ul className="list">
{myList}
</ul>
);
}
}
class Todo extends React.Component {
constructor() {
super();
this.handleClick = this.handleClick.bind(this);
}
handleClick(event) {
this.props.clickHandler(event.target.id);
}
render() {
return (
<li>
<button onClick={this.handleClick}
id={this.props.id}>
Click me
</button> ---
{String(this.props.done)} ---
{this.props.content}
</li>
);
}
}
ReactDOM.render(
<TodoList />,
document.getElementById('app')
);

Categories