Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

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

javascript - Select specific checkbox based on index in React using onChange

I have a list where I'm iterating though every item and it has a checkbox to select a particular list item. The problem I'm facing now is, when I select one item, it checks all the items in the list. How do I check only particular item that is selected?

Excerpt from my code

export default function App() {
  const [checked, setChecked] = useState(false);
  const names = ["John", "Doe", "Jim"];
  const handleCheck = (event, index) => {
    console.log(event.target.checked);
    console.log(index);
    setChecked(event.target.checked);
    return event.target.checked;
  };
  return (
    <div className="App">
      {names.map((values, index) => (
        <div>
          <input
            type="checkbox"
            checked={checked}
            onChange={(event) => handleCheck(event, index)}
          />
          {values}
        </div>
      ))}
    </div>
  );
}

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

question from:https://stackoverflow.com/questions/66056415/select-specific-checkbox-based-on-index-in-react-using-onchange

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

1 Answer

0 votes
by (71.8m points)

You are passing the input tag checked value with one state boolean variable.

Make checked state as an array and indicate it using index for input tag.

On handleCheck() method, update the corresponding index item of the state.

import { useState } from "react";
import "./styles.css";

export default function App() {
  const [allchecked, setAllchecked] = useState(false);
  const [checked, setChecked] = useState([false, false, false]);
  const names = ["John", "Doe", "Jim"];
  const handleCheck = (event, index) => {
    const _checked = [...checked];
    _checked[index] = event.target.checked;
    setChecked(_checked);
  };

  const selectAll = (event) => {
    setAllchecked(event.target.checked);
    const isChecked = event.target.checked;
    console.log(isChecked);
    setChecked([isChecked, isChecked, isChecked]);
  };
  return (
    <div className="App">
      <input type="checkbox" checked={allchecked} onChange={selectAll} />
      Select All
      {names.map((values, index) => (
        <div>
          <input
            type="checkbox"
            checked={checked[index]}
            onChange={(event) => handleCheck(event, index)}
          />
          {values}
        </div>
      ))}
    </div>
  );
}



与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...