jeudi 9 septembre 2021

Change a checkbox checked state from a useEffect hook in React?

The value of context.number is 1. I want to set the input checked value to true based off the context.number. So if context.number is 1, the checkbox is checked for Module 1, showing that Module 1 is completed. I can only change the input value from the onChange event though, so i assume i need a useEffect hook so it does it automatically when context.number changes?

import React, { useState, useContext, useEffect } from "react";
import { Link } from "react-router-dom";
import { AppContext } from "../context/AppContext";

export default function Menu() {

  const context = useContext(AppContext);

  //Determine the modules
  const modules = [
    {
      title: `Introduction`,
      subtitle: "Lesson 1",
    },
    {
      title: `Overview`,
      subtitle: "Lesson 2",
    }
  ];

  //Create a checked state for each module
  const [checkedState, setCheckedState] = useState(new Array(modules.length).fill(false));

  //Change checked value method
  const handleOnChange = (position) => {

    //map through checked states array, if position === mapped item index, flip the value
  const updatedCheckedState = checkedState.map((item, index) => (index === position ? 
  !item : item));

    //set that items state to the new value in the array
    setCheckedState(updatedCheckedState);
  };

  return (
    <>
        <div>
            {modules.map((module, index) => (
              <div className={styles.menuCard}>
                <Link key={index} to={`/Module/${index + 1}`}>
                  <h2>{module.title}</h2>
                  <p>{module.subtitle}</p>
                </Link>
                <input
                  id={`check${index}`}
                  type="checkbox"
                  onChange={() => handleOnChange(index)}
                  checked={checkedState[index]}
                />
              </div>
            ))}
        </div>
    </>
  );
}



Aucun commentaire:

Enregistrer un commentaire