PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Wednesday, August 3, 2022

[FIXED] How do I manage the state of each row in react js?

 August 03, 2022     html, html-table, javascript, reactjs     No comments   

Issue

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>
  );
}

Solution

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.



Answered By - codemonkey
Answer Checked By - Robin (PHPFixing Admin)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing