Less annoying CSS in React with CSS modules

A fundamental problem with CSS is that it’s globally scoped.

So, if you have a number of components in your React app, you would have to think of unique classes to name your components.

And the bigger your app gets, the harder.

This is where CSS mo…


This content originally appeared on DEV Community and was authored by fawazsullia

A fundamental problem with CSS is that it's globally scoped.

So, if you have a number of components in your React app, you would have to think of unique classes to name your components.

And the bigger your app gets, the harder.

This is where CSS modules come in.

CSS modules let you create CSS files that are locally scoped.

Here's how you do it;

  1. Create a CSS file with .module.css extension
  2. In your component, use import * as anyName from 'relative path'
  3. And in yout jsx elements, use className={anyName.nameofclass}
  4. In your module.css file, use .nameofclass to select the elements

Note that, you can select child elements with .nameofclass element name as well (.container button)

This way, you don't have to worry about thinking of unique names to name your class.

If you found this useful, let me know in the comments. if there's a better way to CSS in react, drop a comment


This content originally appeared on DEV Community and was authored by fawazsullia


Print Share Comment Cite Upload Translate Updates
APA

fawazsullia | Sciencx (2021-05-18T18:15:10+00:00) Less annoying CSS in React with CSS modules. Retrieved from https://www.scien.cx/2021/05/18/less-annoying-css-in-react-with-css-modules/

MLA
" » Less annoying CSS in React with CSS modules." fawazsullia | Sciencx - Tuesday May 18, 2021, https://www.scien.cx/2021/05/18/less-annoying-css-in-react-with-css-modules/
HARVARD
fawazsullia | Sciencx Tuesday May 18, 2021 » Less annoying CSS in React with CSS modules., viewed ,<https://www.scien.cx/2021/05/18/less-annoying-css-in-react-with-css-modules/>
VANCOUVER
fawazsullia | Sciencx - » Less annoying CSS in React with CSS modules. [Internet]. [Accessed ]. Available from: https://www.scien.cx/2021/05/18/less-annoying-css-in-react-with-css-modules/
CHICAGO
" » Less annoying CSS in React with CSS modules." fawazsullia | Sciencx - Accessed . https://www.scien.cx/2021/05/18/less-annoying-css-in-react-with-css-modules/
IEEE
" » Less annoying CSS in React with CSS modules." fawazsullia | Sciencx [Online]. Available: https://www.scien.cx/2021/05/18/less-annoying-css-in-react-with-css-modules/. [Accessed: ]
rf:citation
» Less annoying CSS in React with CSS modules | fawazsullia | Sciencx | https://www.scien.cx/2021/05/18/less-annoying-css-in-react-with-css-modules/ |

Please log in to upload a file.




There are no updates yet.
Click the Upload button above to add an update.

You must be logged in to translate posts. Please log in or register.