0

I'm trying to update checked property in list of todos array whenever an item is checked.

How do I update a specific item at that particular index.

For example,

[{name: 'todo1', checked: false},{name: 'todo2', checked: false}]

When I checked todo2, the updated array should be

[{name: 'todo1', checked: false},{name: 'todo2', checked: true}]

Code

  const [todos, setTodos] = useState([]);
  const [checked, setChecked] = useState(false);
  const handleChange = (event, index) => {
    console.log("index", index);
    setChecked(event.target.checked);
  };
  console.log(todos);
  return (
    <>
      {todos.map(
        (item, index) =>
          item.name && (
            <div key={index}>
              <Checkbox onChange={(e) => handleChange(e, index)} />
              {item.name}
            </div>
          )
      )}
      <Formik
        initialValues={{
          todo: ""
        }}
        onSubmit={(values, { resetForm }) => {
          setTodos([...todos, { name: values.todo, checked: checked }]);
          resetForm({ values: "" });
        }}
      >
        <Form>
          <label htmlFor="todo"></label>
          <Field id="todo" name="todo" placeholder="item" />
          <button type="submit">Submit</button>
        </Form>
      </Formik>
    </>
  );
}

I created a working example using CodeSandbox. Could anyone please help?

2 Answers 2

1

Here is how you can toggle the checked value.


const handleChange = (event, index) => {
    console.log("index", index);
    let temp = [...todos];
    temp[index]["checked"] = !temp[index]["checked"];
    setChecked(temp);
    console.log(todos);
  };

Output:

Screenshot

Codesandbox Link

Sign up to request clarification or add additional context in comments.

2 Comments

This is great!!
Glad it helped, happy coding :)
0

here is the best way to do it with good practice on immutable state :

const handleChange = (event, index) => {
   const updatedTodos = todos.map((todo, todoIndex) => index === todoIndex ? {...todo, checked: true} : todo )
   setState(updatedTodos)
};

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.