Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
740 views
in Technique[技术] by (71.8m points)

limit reactjs input element of type checkbox to 2 checked while using usestate array

my purpose is to allow two days of the week to be a weekend

the problem is with this approach i am unable to limit the weekend array to hold only two days its always going beyond

i think the problem is that the state is async and setState and useEffect are having different values but unable to solve the problem

const weekendDays = [
    "Saturday",
    "Sunday",
    "Monday",
    "Tuesday",
    "Wednesday",
    "Thursday",
    "Friday",
  ];
const [weekend, setWeekend] = useState([]);

const handleWeekendSelection = ({ target }) => {
    if (target.checked) {
      !weekend.includes(target.value) &&
        setWeekend((prev) => [...prev, target.value]);
    } else {
      setWeekend((prev) => [...prev].filter((day) => day !== target.value));
    }
  };

  useEffect(() => {
    console.log(weekend.length);
    if (weekend.length > 2) {
      const checkboxes = document.querySelectorAll(
        "input[type=checkbox]:checked"
      );
      const lastCheckbox = checkboxes[checkboxes.length - 1];
      lastCheckbox.checked = false;
setWeekend((prev) => {
        const correctedWeekend = prev;
        correctedWeekend.length > 2 && correctedWeekend.pop();
        return [...correctedWeekend];
  });
    }
  }, [weekend.length]);

        <div>
          {weekendDays.map((day, index) => {
            return (
              <div key={index}>
                <input
                  type="checkbox"
                  value={index}
                  onChange={handleWeekendSelection}
                />
                <label>{day}</label>
              </div>
            );
          })}
        </div>

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Instead of using useEffect it would be proper to handle it while setting in the state. Something like this

const handleWeekendSelection = ({ target }) => {
    if (target.checked) {
      if(!weekend.includes(target.value)){
        let newWeekend = [...weekend, target.value]
        if(weekend.length === ) newWeekend = [weekend[1], target.value]
        setWeekend(newWeekend);
      }
        
    } else {
      setWeekend((prev) => [...prev].filter((day) => day !== target.value));
    }
  };

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...