Search code examples
cssreactjsreact-component

React Table - User COntrolled Header background Color


I have a re-useable table component that I am styling with vanilla CSS. I have six possible colors that I would like users to be able to pick from to change the table header background color if wanted. Ideally, this color choice should be a prop on the component, but I'm not sure how to do this.

In my CSS file I have the color variables defined:

th {
 --deq-primary: #0080b7;
  --daq-primary: #1ab7da;
  --ddw-primary: #147995;
  --dwq-primary: #034a64;
  --derr-primary: #05a68b;
  --dwmrc-primary: #f26322;
}

th {
  background-color: var(--deq-primary);
  color: white;
  border: 1px solid #cecece;
}

Is it possible to set a prop on my table to accept one of these values so that the header background color can be changes within the component?

Something like

<MyTable headerColor="ddw-primary" />

the the header color would change to the ddw-primary color

UPDATE I was able to implement Hugo Elhaj-Lahsen suggestion. The variable name is being passed as a string and I updated the example he provided to account for the -- that is required in the variable name. So the final style tag in the code looks like


return <table style={{backgroundColor: `var(--${headerColor})` }}>
  {// ...}
</table>


....
>

In the component I'm passing the var name as a string:

<MyTable
        columns={columns}
        data={data}
        headerColor="my-color-variable-name"
        />


Solution

  • A possible React solution without libs would be to pass the CSS variable name as props, and reference it in the style of your component. Suppose we have:

    <MyTable headerColor="ddw-primary" />
    

    and your CSS variables defined in the MyTable component. Assuming you style via the style= property, you can do:

    return <table style={{backgroundColor: `var(${headerColor})` }}>
      {// ...}
    </table>