Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Apply CSS Module class name by directly accessing the DOM

I have a component that makes use of CSS-Modules, by means of the babel-plugin-react-css-modules plugin.

At some points during the lifetime of the component I want to be able to calculate new dimensions for it, by accessing the DOM directly.

In my SCSS stylesheet I have a class named .full-width that I want to apply to the component's DOM element, in order to make a calculation, and then remove it again.

Now, since adding the class and removing it a fraction of a second later does not affect the component or its state, I want to add and remove the class by directly accessing the DOM and not going through the hoops of somehow relating it to the component's state.

If I do this.DOMReference.classList.add('full-width'); the class full-width is added to it, but I want to add the modularised version of the class, as it would be applied if I did styleName="full-width" (for example Component__full-width___Pjd10 )

Is there any way to do this without making .full-width a global declaration?

Would I be able to do this with react-css-modules?

like image 727
Dimitris Karagiannis Avatar asked Sep 15 '25 10:09

Dimitris Karagiannis


1 Answers

Well, I realised I can import the styles under a variable, instead of anonymously, for example

import styles from './styles.scss' instead of import './styles.scss' and then I can use it as such

this.DOMReference.classList.add(styles['full-width']);

I also don't have to use styleName="styles.someClass" either, I can simply use styleName="someClass" (as long as there is only one stylesheet file imported, otherwise you need to do it as the former)

like image 187
Dimitris Karagiannis Avatar answered Sep 17 '25 03:09

Dimitris Karagiannis