I just want to ask if is it possible to change the color of the font when the value changes ? just like how trading platform works it will ticks the font . It changes the color from white to green ( when the value goes up and ) so I want to change the color of failed to red for 1 second when the value goes up and I want to change the color of sent to green for 1 second when the value goes up . is it possible to add the code inside the table cell ? thank you
here’s the code of the table Cell
JavaScript
x
2
1
<TableCell sx={{ border:0.1,fontSize: 11.5, fontWeight: 200 }} align="center" style={{ paddingTop: 0,paddingBottom: 0,paddingLeft: 0,paddingRight:0, }}>{port.chargeCnt}</TableCell>
2
Advertisement
Answer
You need to:
- Track the previous value (use the
usePrevious
hook) - Compare it to the current value whenever the current value changes and use that to determine what colour to set it to
- Add a
setTimeout
function to reset the colour to the default after a second - Handle the case where the value changes again before the reset has happened (by cancelling the timeout waiting to reset it).
- Cancel that timeout when the component unmounts (so you don’t try to set a state that no longer exists).
Such:
JavaScript
1
25
25
1
import { usePrevious } from 'react-use';
2
import { useState, useEffect } from 'react';
3
4
const ChangingValue = ({ value }) => {
5
const previous = usePrevious(value);
6
const [color, setColour] = useState('black');
7
const [timeoutId, setTimeoutId] = useState(0);
8
useEffect(() => {
9
clearTimeout(timeoutId);
10
if (value > previous) {
11
setColour('green');
12
} else if (value < previous) {
13
setColour('red');
14
} else {
15
setColour('black');
16
}
17
const newTimeoutId = setTimeout(() => {
18
setColour('black');
19
}, 1000);
20
setTimeoutId('newTimeoutId');
21
return () => clearTimeout(newTimeoutId);
22
}, [value]);
23
return <div style={{ color }}>{value}</div>;
24
};
25