Apply CSS Module class name by directly accessing the DOM

2.7k views Asked by At

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?

2

There are 2 answers

0
Dimitris Karagiannis On BEST ANSWER

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)

0
Marcelo Albuquerque On

Use in Next.js

If you use Next.js workes perfect to.

Import CSS Module

import styles from './styles.module.css'

On your Function

element.classList.add(styles['full-width'])