selecting one row in the table without using extra npm packages

you are using a single state to check the selected row which cant be done as a single state can not hold the value for all the rows. I see you also have a status select inside each object which you use to check/uncheck the checkboxes. We can use the same to show colored rows as well. Here is an updated codesandbox you can have a look at. Let me know if any questions.

export default function App() {
  const [studentState, setStudentState] = useState([]);

  useEffect(() => {
    let studentState = [
      { id: 1, firstname: "Stone", lastname: "cold", major: "wwf" },
      { id: 2, firstname: "Addrian", lastname: "Fox", major: "wwf" },
      { id: 3, firstname: "Harry", lastname: "Pit", major: "wwf" }
    ];

    setStudentState(
      studentState.map((d) => {
        return {
          select: false,
          id: d.id,
          firstname: d.firstname,
          lastname: d.lastname,
          major: d.major
        };
      })
    );
  }, []);

  return (
    <div className="container">
      <table className="table table-bordered">
        <thead>
          <tr>
            <th scope="col">
              <input
                type="checkbox"
                onChange={(e) => {
                  let checked = e.target.checked;
                  setStudentState(
                    studentState.map((d) => {
                      d.select = checked;
                      return d;
                    })
                  );
                }}
              ></input>
            </th>
            <th scope="col">First</th>
            <th scope="col">Last</th>
            <th scope="col">Handle</th>
          </tr>
        </thead>
        <tbody>
          {studentState.map((d, i) => (
            <tr key={d.id} className={d.select ? "blue" : null}>
              <th scope="row">
                <input
                  onChange={(event) => {
                    let checked = event.target.checked;
                    setStudentState(
                      studentState.map((data) => {
                        if (d.id === data.id) {
                          data.select = checked;
                        }
                        return data;
                      })
                    );
                  }}
                  type="checkbox"
                  checked={d.select}
                  id={d.id}
                ></input>
              </th>
              <td>{d.firstname}</td>
              <td>{d.lastname}</td>
              <td>{d.major}</td>
            </tr>
          ))}
        </tbody>
      </table>
    </div>
  );
}

CLICK HERE to find out more related problems solutions.

Leave a Comment

Your email address will not be published.

Scroll to Top