jeudi 11 mars 2021

finding the clicked element in an array of references (useRef)

How can I find the clicked item if I have an array of referenced values, I used useRef

import { useRef, useState, useEffect } from 'react';

function App() {
  const checkboxes = useRef({});
  var arr = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j']
  var myArrValues = []
  const [arrValues, setArrValues] = useState(false)

  for (let i = 0; i < arr.length; i++)
    myArrValues.push(i % 2 === 0)

  useEffect(() => {
    setArrValues(myArrValues)
  }, [])

  const setcheckBoxValue = (e) => {
    console.log(checkboxes);
  }

  return (
    <div className="App">
      {arr.map( (x, idx) =>
        <input 
          type="checkbox" 
          id={idx.toString()} 
          name={idx.toString()} 
          checked={arrValues[idx]}
          ref={ (el) => checkboxes.current[idx] = el } 
          onChange={(e) => setcheckBoxValue(e)}
        ></input>)
      }
    </div>
  );
}

export default App;

In the setcheckBoxValue method, I need to know which checkbox was clicked Thanks in advance

Rafael




Aucun commentaire:

Enregistrer un commentaire