jeudi 11 mars 2021

Handling an indetermined amount of states for n checkboxes in React

I have this solution for handling a fix number of states for a fix number of checkboxes:

import { useState } from 'react';

function App() {
  const [arrValues, setArrValues] = useState(
    // use a function here to only create the initial array on mount
    () => Array.from(
      { length: 10 }
    )
  );

  const setcheckBoxValue = (i) => {
    setArrValues(
      arrValues.map((v, j) => j !== i ? v : !v)
    );
    console.log(arrValues);
  }

  return (
    <div className="App">
      {arrValues.map( (val, i) =>
        <input 
          key={i}
          type="checkbox" 
          checked={val}
          onChange={() => setcheckBoxValue(i)}
        >

        </input>)
      }
    </div>
  );
}

export default App;

In the code it is 10, but, what if the length of the array is not known until I read some value in a database,

Rafael




Aucun commentaire:

Enregistrer un commentaire