CSS Variables in React.js

prashantbhat84

Prashant Bhat

Posted on April 29, 2021

CSS Variables in React.js

Introduction

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

💖 💪 🙅 🚩
prashantbhat84
Prashant Bhat

Posted on April 29, 2021

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related