1

I'm trying to make a to-do app with react. It has basic functionalities: item adding, item removing, and complete task. In my code, functionalities working clearly but when I click the complete button, and the same time remove that item it is working buggy. Item removes but completed checkbox adding the next item.

Image Here

Code Section: App.js

import './App.css';
import Header from './components/Header'; 
import List from './components/List';
import React, { useState, useEffect } from 'react';

function App() {

  const [elements, setElements] = useState([]);

  useEffect(() => {
    console.log(elements);
  }, [elements]);

  const setElement = (element) => {
    setElements([...elements, element]);
  }

  const completeElement = (index) => {
    let array = [...elements];
    array[index].isCompleted = !array[index].isCompleted;
    setElements(array);
 }

  const deleteElement = (index) => {
    let array = [...elements];
    array.splice(index, 1);
    setElements(array);
  }

  return (
    <div className="todoapp">
      <Header save={setElement} />
      <List elements={elements} complete={completeElement} remove={deleteElement} />
    </div>
  );
}

export default App;

List.js:

{elements.map((item, index) => {
    const status = item.isCompleted ? "completed" : "";
    return(
        <li className={status}  key={index}>
            <div className="view">
                 <input className="toggle" type="checkbox" onClick={() => {complete(index)}} />
                 <label>{item.text}</label>
                 <button className="destroy" onClick={() => {remove(index)}}></button>
              </div>
          </li> 
      );
 })}

On List.js, className={status} working buggy.

Thanks for help.

2 Answers 2

1

You should add checked in input:

<input ... checked={item.isCompleted} />
Sign up to request clarification or add additional context in comments.

1 Comment

Thank you! I tried defaultChecked. But it's not worked. Problem solved!
0

Don't use index for key in your map items, use item id instead of it. It's the cause of problem

You can read here why do we need keys in Reac lists https://adhithiravi.medium.com/why-do-i-need-keys-in-react-lists-dbb522188bbb

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.