Skip to content
Advertisement

Change table row color by dynamically updating the className

I created this Typescript class in an attempt to change the row color in a table. My aim was to dyanmically update the className for the tr. Everything displays as expected but nothing happend when I check/uncheck the box. How do I fix this?

import React from 'react';
import './App.css';

let classname: string = "checkbox-row1";

function getColor(pvalue: boolean) {
  if (pvalue) {
    classname = "checkbox-row1-red";
  }
  else {
    classname = "checkbox-row1-blue";
  }
}

export default function App() {

  return (
    <div className="App">
      <header className="App-header">
        <div className="checkbox-div">
          <table className="checkbox-table">
            <tr className={classname}>
              <td className="checkbox-row1"><label className="my-label">Check: <input type="checkbox" onClick={() => getColor(true)} name="change-color"></input></label></td>
              <td className="tr2-td2">2</td>
              <td className="tr3-td3">3</td>
            </tr>
          </table>
        </div>
      </header>
    </div>
  );
}
.App {
  text-align: center;
}

.App-logo {
  height: 40vmin;
  pointer-events: none;
}

@media (prefers-reduced-motion: no-preference) {
  .App-logo {
    animation: App-logo-spin infinite 20s linear;
  }
}

.App-header {
  background-color: #282c34;
  min-height: 100vh;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  font-size: calc(10px + 2vmin);
  color: white;
}

.App-link {
  color: #61dafb;
}

@keyframes App-logo-spin {
  from {
    transform: rotate(0deg);
  }
  to {
    transform: rotate(360deg);
  }
}

.checkbox-row1 {
  background-color: #ffffff;
}

.checkbox-row1-blue {
  background-color: blue;
}

.checkbox-row1-red {
  background-color: red;
}

.my-label {
  color: black;
}

Advertisement

Answer

You want to use the React hook useState() inside a React component. (https://reactjs.org/docs/hooks-reference.html#usestate) When state changes, the re-render will update your row class as expected.

import { useState } from "react";
export default function App() {
    const [classname,setClassname] = useState<string>("checkbox-row1");

    function getColor(pvalue: boolean) {
      if (pvalue) {
         setClassname("checkbox-row1-red");
      }
      else {
        setClassname("checkbox-row1-blue");
      }

return ( ...
User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement