DEV Community

Prashant Bhat
Prashant Bhat

Posted on

CSS Variables in React.js


The purpose of this post is to show the use of CSS varibles in React.js applications

CSS Variables with HTML and CSS

In a typical app which consists of HTML ,CSS and JS the CSS file is linked to the html file and we have the root pseudo selector as shown below.
Alt Text

Now in a react app its a SPA but its component based structure. Each component has a separate CSS file attached to it.

So the question is how can we have a common set of CSS variables which can be used throughout the application?

CSS Variables in React applications

This is a standard react application structure.
Alt Text
We have the index.css file where we can define the root pseudo selector. In that we can define the CSS variables which we can use throughout the application.
Alt Text
Now we need to import the index.css file into the index.js file as shown below.
Alt Text

Now we can use these declared CSS variables throughout the app. Because React being a SPA all the variables declared in index.css will be applicable throughout the application as shown in the app.css file image below.
Alt Text

Thank you for reading this article

Top comments (1)

addtvb profile image

Great article, short and to the point👍