Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

218
Vistas
toggling a checkbox at a time in react

I have a react component that renders material UI table. This table is populated with data that is fetched from an API. In one of the table cells, I have a Material UI switch for toggling whether a user is blocked or active. However, whenever I check one of the switches, all the switches simultaneously get checked which is not what I intend to achieve. I want to be able to check each switch individually without it affecting the state of the other switches. Is there a great way to get this done? Table data representation

Below is a sample code snippet:

    const Customers = ({customers}) => {
        const [checked, setChecked] = useState(false);

        const handleSwitchChange = (event) => {
        setChecked(event.target.checked);
    }
        return customers.map((customer) => {
    const {_id, name, email, } = customer;
    return (
      <TableRow hover role="checkbox" tabIndex={-1} key={_id}>
        <TableCell style={{ minWidth: 150 }}>{name}</TableCell>
        <TableCell>{email}</TableCell>
        <TableCell>Activated</TableCell>
        <TableCell align="center">
          <Switch
            color="error"
            onChange={handleSwitchChange}
            checked={checked}
          />
        </TableCell>
        <TableCell>
          <CustomIconButton
            startIcon={<VisibilitySharpIcon />}
            title="Details"
          />
          <CustomIconButton
            startIcon={<EditSharpIcon />}
            title="Edit"
          />
          <CustomIconButton
            startIcon={<MailSharpIcon />}
            title="Send"
          />
          <IconButton>
            <DeleteSharpIcon />
          </IconButton>
        </TableCell>
      </TableRow>
    );
  });
}

about 4 years ago · Juan Pablo Isaza
3 Respuestas
Responde la pregunta

0

What you are doing is the checked variable is related to the React Functional Components, so when you setChecked(true) for example you will set it for all the checkboxes.

Each customer should have a checked value. so when you handle the switch you should map through your customers to find the intended one (using the id, you will passe it through the handleSwitch function). then when you find it you will get a filtered list then you should access the first one (filteredList.first). and set checked =!checked. Solution 2 you pass the index to the function handleSwitch and set customers[index].checked to the opposite.

about 4 years ago · Juan Pablo Isaza Denunciar

0

You are passing the common checked option to all the rows. Please pass additional parameters like isChecked indigual to your rows and change that parameter on that function by passing key to that.

about 4 years ago · Juan Pablo Isaza Denunciar

0

You should create a separate component (SwitchComp) to isolate the toggle logic like below.

import { useState } from "react";

const SwitchComp = ({ color = "error" }) => {
  const [checked, setChecked] = useState(false);

  const handleSwitchChange = (event) => {
    setChecked(event.target.checked);
  };

  return (
    <Switch color={color} onChange={handleSwitchChange} checked={checked} />
  );
};

Use SwitchComp where you used the Switch component previously like below.

const Customers = ({ customers }) => {
  return customers.map((customer) => {
    const { _id, name, email } = customer;
    return (
      <TableRow hover role="checkbox" tabIndex={-1} key={_id}>
        <TableCell style={{ minWidth: 150 }}>{name}</TableCell>
        <TableCell>{email}</TableCell>
        <TableCell>Activated</TableCell>
        <TableCell align="center">
          <SwitchComp color="error" />
        </TableCell>
        <TableCell>
          <CustomIconButton
            startIcon={<VisibilitySharpIcon />}
            title="Details"
          />
          <CustomIconButton startIcon={<EditSharpIcon />} title="Edit" />
          <CustomIconButton startIcon={<MailSharpIcon />} title="Send" />
          <IconButton>
            <DeleteSharpIcon />
          </IconButton>
        </TableCell>
      </TableRow>
    );
  });
};

about 4 years ago · Juan Pablo Isaza Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda