Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

163
Visualizações
How do I manage the state of each row in react js?

I'm mapping through data from a db into a html table where each has row has a toggle button to mark if they're absent or not. However I'm not sure how to save the state of each row's toggle button since they're all going to be different.

function Component() {
  const [students, setStudents] = useState([]);
  const [absent, setAbsent] = useState(false);
  const updateAbsent = () => {
    console.log(absent);
  };

  return (
    <div className="attendance-today-container">
      <h1>Daily attendance</h1>
      <table ref={table}>
        <tr>
          <th>First Name</th>
          <th>Last Name</th>
          <th>Absent?</th>
        </tr>
        {students.map((student, i) => {
          return (
            <tr>
              <td key={i}>{student.firstName}</td>
              <td>{student.lastName}</td>
              <td>
                <label class="switch">
                  <input
                    type="checkbox"
                    onClick={() => {
                      setAbsent(!absent);
                    }}
                  />
                  <span class="slider round"></span>
                </label>
              </td>
            </tr>
          );
        })}
      </table>
      <button onClick={updateAbsent}>Send</button>
    </div>
  );
}
about 4 years ago · Juan Pablo Isaza
2 Respostas
Responde à pergunta

0

An easy way would be to store the student data and if they are present or absent in the same state.

Each student could have an id in order to identify him easily. A function could go through the student state array and identify with the id which student was marked absent or present.

const data = [
    { id: 1, firstName: 'John', lastName: 'Doe', absent: false },
    { id: 2, firstName: 'Jane', lastName: 'Doe', absent: false },
];

const StudentList = () => {
    const [students, setStudents] = useState(data);
    const updateAbsent = () => {
        const absents = students.filter((student) => student.absent === true);
        console.log(absents);
    };
    const handleToggleAbsent = (toggleStudent) => {
        setStudents((prevStudents) =>
            prevStudents.map((student) => {
                if (student.id !== toggleStudent.id) return student;
                return { ...student, absent: !student.absent };
            })
        );
    };

    return (
        <div className="attendance-today-container">
            <h1>Daily attendance</h1>
            <table>
                <thead>
                    <tr>
                        <th>First Name</th>
                        <th>Last Name</th>
                        <th>Absent?</th>
                    </tr>
                </thead>
                <tbody>
                    {students.map((student) => {
                        return (
                            <StudentItem
                                student={student}
                                key={student.id}
                                onToggleAbsent={handleToggleAbsent}
                            />
                        );
                    })}
                </tbody>
            </table>
            <button onClick={updateAbsent}>Send</button>
        </div>
    );
};

const StudentItem = (props) => {
    const { student, onToggleAbsent } = props;
    return (
        <tr>
            <td>{student.firstName}</td>
            <td>{student.lastName}</td>
            <td>
                <label className="switch">
                    <input
                        type="checkbox"
                        onClick={onToggleAbsent.bind(null, student)}
                    />
                    <span className="slider round"></span>
                </label>
            </td>
        </tr>
    );
};

export default StudentList;
about 4 years ago · Juan Pablo Isaza Relatório

0

The concept is along the lines of what Sheik Yerbouti suggested and what SamiElk has demonstrated.

Take the array of student objects and add a property called absent to each and set it to false by default. Then have the corresponding check boxes toggle the absent properly for each student based on the index of the the object in the array AND the present value of its absent property. I have created a function called getData that will simulate your API call to get the student data. Here is the code:

import { useEffect, useState } from "react";
import "./styles.css";


const getData = () => {
  return new Promise(resolve => {
    resolve([{firstName: "John", lastName: "Marks"}, {firstName: "Garry", lastName: "Nelson"}]);
  })
}

export default function App() {
  const [students, setStudents] = useState([]);

  const markAbsent = (i) => {
    setStudents(prev => 
      prev.map((s, index) => ({...s, absent: i === index ? !s.absent : s.absent}))
    )
  }

  useEffect(() => {
    getData()
    .then(data => {
      data = data.map(i => ({absent: false, ...i}));
      setStudents(data);
    })
  }, [])

  return (
    <div className="attendance-today-container">
      <h1>Daily attendance</h1>
      <table>
        <tr>
          <th>First Name</th>
          <th>Last Name</th>
          <th>Absent?</th>
        </tr>
        {students.map((student, i) => {
          return (
            <tr>
              <td key={i}>{student.firstName}</td>
              <td>{student.lastName}</td>
              <td>
                <label class="switch">
                  <input
                    type="checkbox"
                    defaultChecked={student.absent}
                    onClick={() => markAbsent(i)}
                  />
                  <span className="slider round"></span>
                </label>
              </td>
            </tr>
          );
        })}
      </table>
      <button onClick={() => false}>Send</button>
    </div>
  );
}

Note that I am not certain what the Send button is supposed to do so I left it non-functional. Here is a Sandbox link for you to play with.

about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda