mercredi 24 novembre 2021

Check if all checkboxes are checked and console.log("all checked") Javascript/React

The following component is meant to be a To-Do list. I got multiple checkboxes. As soon as all checkboxes are checked, a console.log("all checked") should appear.

My idea is to check if the todo.lengh === checked.length, but it doesn't work.

Problem: trying to console.log(checked.length) doesn't work either so there must be the problem.

Can someone help me how to reach the checked.length?

import React from 'react';
import { AiOutlinePlusCircle } from 'react-icons/ai';
import { useState } from 'react';

function Checkboxes() {
  const [todo, setToDo] = React.useState('');
  const [todos, setToDos] = React.useState([]);
  const [checked, setChecked] = useState(false);

  function handleToDoSubmit(e) {
    e.preventDefault();

    const newToDo = {
      id: new Date().getTime(),
      text: todo,
      completed: false,
    };

    setToDos([...todos].concat(newToDo));
    setToDo('');
  }

  function toggleCompleteToDo(id) {
    const updatedToDos = [...todos].map((todo) => {
      if (todo.id === id) {
        todo.completed = !todo.completed;
      }
      return todo;
    });
    setToDos(updatedToDos);
  }

  function allChecked(checked) {
    if (todo.length === checked.length) {
      console.log('all checked');
    }
  }

  return (
    <div className="ToDoList">
      <form className="goalInputToDo" onSubmit={handleToDoSubmit}>
        <input
          className="goalInput"
          type="text"
          onChange={(e) => setToDo(e.target.value)}
          value={todo}
        />
        <button className="AddGoalBtn" type="submit">
          .
          <AiOutlinePlusCircle size="2em" />
        </button>
      </form>

      {todos.map((todo) => (
        <div className="goalItem">
          <div key={todo.id}>
            <div>{todo.text}</div>
            <input
              type="checkbox"
              onChange={() => {
                toggleCompleteToDo(todo.id), allChecked(todo.checked);
              }}
              checked={todo.completed}
            />
          </div>
        </div>
      ))}
    </div>
  );
}
export default Checkboxes;



Aucun commentaire:

Enregistrer un commentaire