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?
JavaScript
x
33
33
1
import React from 'react';
2
import './App.css';
3
4
let classname: string = "checkbox-row1";
5
6
function getColor(pvalue: boolean) {
7
if (pvalue) {
8
classname = "checkbox-row1-red";
9
}
10
else {
11
classname = "checkbox-row1-blue";
12
}
13
}
14
15
export default function App() {
16
17
return (
18
<div className="App">
19
<header className="App-header">
20
<div className="checkbox-div">
21
<table className="checkbox-table">
22
<tr className={classname}>
23
<td className="checkbox-row1"><label className="my-label">Check: <input type="checkbox" onClick={() => getColor(true)} name="change-color"></input></label></td>
24
<td className="tr2-td2">2</td>
25
<td className="tr3-td3">3</td>
26
</tr>
27
</table>
28
</div>
29
</header>
30
</div>
31
);
32
}
33
JavaScript
1
56
56
1
.App {
2
text-align: center;
3
}
4
5
.App-logo {
6
height: 40vmin;
7
pointer-events: none;
8
}
9
10
@media (prefers-reduced-motion: no-preference) {
11
.App-logo {
12
animation: App-logo-spin infinite 20s linear;
13
}
14
}
15
16
.App-header {
17
background-color: #282c34;
18
min-height: 100vh;
19
display: flex;
20
flex-direction: column;
21
align-items: center;
22
justify-content: center;
23
font-size: calc(10px + 2vmin);
24
color: white;
25
}
26
27
.App-link {
28
color: #61dafb;
29
}
30
31
@keyframes App-logo-spin {
32
from {
33
transform: rotate(0deg);
34
}
35
to {
36
transform: rotate(360deg);
37
}
38
}
39
40
.checkbox-row1 {
41
background-color: #ffffff;
42
}
43
44
.checkbox-row1-blue {
45
background-color: blue;
46
}
47
48
.checkbox-row1-red {
49
background-color: red;
50
}
51
52
.my-label {
53
color: black;
54
}
55
56
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.
JavaScript
1
14
14
1
import { useState } from "react";
2
export default function App() {
3
const [classname,setClassname] = useState<string>("checkbox-row1");
4
5
function getColor(pvalue: boolean) {
6
if (pvalue) {
7
setClassname("checkbox-row1-red");
8
}
9
else {
10
setClassname("checkbox-row1-blue");
11
}
12
13
return (
14