6

I'm using webpack with css-loader to load my css styles and add them to React components.

import styles from '../styles/cell.css';

.cell {
    border-radius: 50%;
    background-color: white;
}

<div className={styles.cell} />

I'm calculating the height/width for the cell dynamically. Here they describe how to add styles to components dynamically, but i'd prefer doing this without the style attribute.

I tried doing this in one of the parent components thinking it might alter the css class but that didn't seem to work.

import cell_styles from '../styles/cell.css';
cell_styles.width = this.cellSize + 'px'
cell_styles.height = this.cellSize + 'px'

Any feedback on how best to do this?

noi.m
  • 3,070
  • 5
  • 34
  • 57

2 Answers2

20

You could try CSS custom properties on the CSS properties that are dynamic (eg, width and height):

// cell.css

.cell {
  width: var(--width);
  height: var(--height);
}

Then you can supply the values of the CSS variables in a parent container (CSS variables also cascade down):

<div style={{ '--width': `${something}px`, '--height': `${something}px` }}>
  <div class="cell"></div>
  <div class="cell"></div>
  <div class="cell"></div>
</div>

Treat it like a "CSS parameter/props" that passes down to children.

One good thing about this approach is you avoid updating and re-rendering the child components.

Kalabasa
  • 506
  • 5
  • 14
  • 3
    This is an awesome option. Especially for pseudo classes like `:hover`, since they could not be accessed via the style attribute. For use with typescript it is necessary to cast the css variable since it is not a css property. `['--width' as any]: ${ something }+'px'` – Dave Gööck Sep 14 '20 at 14:16
9

You should be using the style attribute, that is the purpose of it.

import classLevelStyles from '../styles/cell.css';

const style = {
    width:  this.calcWidth()  + 'px',
    height: this.calcHeight() + 'px',
};

<div className={classLevelStyles} style={style} />
Chris
  • 54,599
  • 30
  • 149
  • 186
  • 2
    Was curious if there was any other way. In anycase this worked for me. Would just like to point out, the property on the element is "style" (not "styles"). Thank you. – noi.m Jan 06 '17 at 13:58