How to define css variables in style attribute in React and typescript

jcubic picture jcubic · Aug 24, 2018 · Viewed 20.4k times · Source

I want to define jsx like this:

<table style={{'--length': array.lenght}}>
   <tbody>
      <tr>{array}</tr>
   </tbody>
</table>

and I use --length in css, I also have cells that have --count that shows count using css pseudo selector (using counter hack).

but typescript show error:

TS2326: Types of property 'style' are incompatible.
  Type '{ '--length': number; }' is not assignable to type 'CSSProperties'.
    Object literal may only specify known properties, and ''--length'' does not exist in type 'CSSProperties'.

is it possible to change type of style attribute to accept css variable (custom properties) or is there a way to force any on style object?

Answer

ixrock picture ixrock · Jan 10, 2019

Like this:

render(){
  var style = { "--my-css-var": 10 } as React.CSSProperties;
  return <div style={style}>...</div>
}