mercredi 16 septembre 2020

React checkbox state with id or other attributes instead of name

In react, is it possible to manage the state of multiple checkboxes with id attribute or other attributes such as data-*?

For the moment all I'm using is the name attribute, however in my project I need to use the id or preferably data-* due to the complexity of the project, but it seems that in react it's isn't possible.

Or am I not understanding in?

import React, { useState } from 'react';
import someData from './someData'

function Checkbox({ name, id, label, checked, onChange }) {
  return (
    <span>
      <input 
        type="checkbox" 
        name={name} 
        id={id} 
        checked={checked} 
        onChange={onChange} 
      />
      <span>{label}</span>
    </span>
  );
}

function App() {
  const [isChecked, setIsChecked] = useState()

  const onCheckboxChange = event => {
    const target = event.currentTarget;
    const name = target.name
    const id = target.id;
    const checked = target.checked;

    setIsChecked({
      ...isChecked,
      [id]: checked // using "id" seems to not work here.
    })
  }

  return (
    someData.map(item => {
      return (
        <Checkbox
          name={item.name}
          id={item.id}
          label={item.name}
          onChange={onCheckboxChange}
          checked={isChecked}
        />
      );
    }
  );
}



Aucun commentaire:

Enregistrer un commentaire