I'm using React Javascript.
I'm trying to apply a background linear pattern to the cells of a table. The goal is to have the cell colored for a given percentage, while the remaining is white.
The function is the following:
const describeColoredSensation = (val,r,g,b,a) => {
const pos = 10 * val;
const def = `rgba(${r},${g},${b},${a}) 0%, rgba(${r},${g},${b},${a}) ${pos}%, rgba(255,255,255,1) ${pos}%, rgba(255,255,255,1) 100%)`
return (
<td
style={{ background: `${def}`}}
>{val}</td>
)
};
The function is call as
<tr>
{describeColoredSensation(item.value,253,253,62,255)}
</tr>
A sample def
variable content is:
"rgba(253,253,62,255) 0%, rgba(253,253,62,255) 80%, rgba(255,255,255,1) 80%, rgba(255,255,255,1) 100%)"
But inspecting the browser the background color is not set (the background-color attribte is not present).
While I have just 4 different colors, I cannot use CSS, because the value of the val
variable changes dynamically.
BTW, if I define const def = "rgba(255,0,0,255)";
it runs correctly, displaying all the cells in red.
Also, if I copy the content of the def
variable in the debugger on the browser, it shows correctly.
So, I believe that the problem is how to make digest the statement to React Javascript.
CodePudding user response:
By default, background
takes only a single color. You should use a gradient if you want to mix colors.
Note, while the rgb color channels are in the range [0,255]
, the alpha channel is only in the range [0,1]
.
const describeColoredSensation = (val, r, g, b, a) => {
const pos = 10 * val;
const def = `linear-gradient(to right, rgba(${r},${g},${b},${a}) 0%, rgba(${r},${g},${b},${a}) ${pos}%, rgba(255,255,255,1) ${pos}%, rgba(255,255,255,1) 100%)`;
return <td style={{ background: def }}>{val}</td>;
};