mardi 21 septembre 2021

How to check checkbox individually in a map array?

Hello I'm creating a table with .map this is how it looks:

enter image description here

I'm experimenting with checkbox I want to send all that data to another piece of code I'm working on did a few attempts with input type = 'checkbox' and failed and saw a few tutorials with Material UI Checkbox and decided to use that one cause it seems more reliable.

Now my question is: How can I check the checkbox individually, when I check on one it checks all of them. I know I'm sending the right parameters because the data I'm getting is the correct one, Example:

enter image description here

The UID is correct, it was false which means is correct (because code is not working yet) and finally is the first one (index 0) which means is grabbing all the right parameters, this is how it looks in the database you can see is grabbing the right UID, etc.

enter image description here

If I remove the conditions of my code it also does work, here how it looks (I clicked on both): enter image description here

The point of my code is to grab the students ID and put them on arrays so I can display them in another piece of code in a map, but for that I need the checkbox to work so that they add students to the Array when is check and to remove that student when is uncheck. I had to explain the whole thing so it makes sense what I'm trying to do, sorry if I took too long to make the question.

All I need is to understand how to make the checkbox works separately, the map array is making it too confusing.

This are the pieces of codes:

//Relevant Function + Variables.

const [studentID, setStudentID] = useState([])
const [ checked, setChecked ] = useState(false)

const setStudent = (estudiante, check, index) => {
  setChecked(prevState => !prevState);
  var checkBox = document.getElementById('checkBox');
     
  if(checkBox.ariaChecked === true){
         let data = studentID;
         data.push(estudiante);
         setStudentID(data);
         console.log("Hi I'm True")
         console.log(estudiante, check, index)
      }  
       else if (checkBox.ariaChecked === false){
        console.log("Hi I'm False")
           console.log(estudiante, check, index)
        }  
}

//Map
<tbody>
   {estudiantes.map((estudiante, index) => (
      <tr>
      
      <td>
      <Checkbox
      checked={checked}
      color = "primary"
      id = "checkBox"
      onChange = {() => setStudent(estudiante.uid, checked, index)}
      inputProps=aria-label
      />
      </td>

      <td>{estudiante.name}</td>
      <td>{estudiante.school}</td>
      <td>{estudiante.grade}</td>

      <td>
      <Button 
       startIcon = {<DeleteIcon />}
       size = "medium"
       variant = "contained"
       color = "secondary"
       onClick = { ()=>{deleteProduct(estudiante.uid)}}>
       Borrar
       </Button>
       </td>

       </tr>
   ))}
</tbody>




Aucun commentaire:

Enregistrer un commentaire