Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

166
Views
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 answers
Answer question

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 Report

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 Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!