Bringing in CSS variables to a Typescript document

In order to streamline the styling process for our app, we have established a theme.css :root file containing a set of commonly used variables that can be accessed across all other .css files.

However, some of our older code follows a similar structure but is stored in a theme.ts file with its own set of variables. The goal is to import the variables from our theme.css file into our theme.ts file so that all manipulations can be centralized within the css file.

After exploring resources like this medium article and this stackoverflow response, I attempted a quick solution by using const s = require('./theme.css'), however, I was unable to correctly assign the variables.

Here's an excerpt from our theme.css file:

:root {
  --primaryColor: #427ee1;
  --secondaryColor: #f2f2f2;
  --chatBackground: #fff;
  --typingAnimationDots: #427ee1;
  --typingAnimationFill: #f2f2f2;
  --userResponseColor: #427ee1;
  --fontType: 'Open Sans';
  --hoverFillColor: #306aca;
  --hoverFontColor: #f2f2f2;
}

And here are unsuccessful attempts at calling variables in our theme.ts file:

const s = require('./theme.css')

const botMessageBackgroud = s.secondaryColor   // returns black as if it's undefined
const botMessageBorder = s['--primaryColor']   // also returns black
const botMessageColor = s[':root']['--primaryColor']   // encounters "cannot read --primaryColor of undefined"

This suggests that my approach to accessing the variables may be incorrect or perhaps an external dependency needs to be imported. Any guidance on resolving this issue would be greatly appreciated.

edit** Another method I tried involved utilizing a function:

const s = require('./theme.css')
console.log('s >>> ', s)

const callVar = (varName: string) => {
  return getComputedStyle(document.documentElement).getPropertyValue(varName)
}
const botMessageBorder = callVar('--primaryColor')
const botMessageColor = callVar('--primaryColor')

edit** An important detail to note is that values in our theme.css file are derived from our api through a mobx state tree:

export const BotCSS = types.model({
  chatBackground: types.optional(types.string, '#fff'),
  fontType: types.optional(types.string, 'Open Sans'),
  hoverFillColor: types.optional(types.string, '#306aca'),
  hoverFontColor: types.optional(types.string, '#f2f2f2'),
  primaryColor: types.optional(types.string, '#427ee1'),
  secondaryColor: types.optional(types.string, '#fff'),
  typingAnimationDots: types.optional(types.string, '#427ee1'),
  typingAnimationFill: types.optional(types.string, '#f2f2f2'),
  userBoxColor: types.optional(types.string, '427ee1'),
  userResponseColor: types.optional(types.string, '#fff'),
  widgetShape: types.optional(types.string, '50%')
})

export type IBotCSS = typeof BotCSS.Type

It seems plausible to directly import these mobx values into the TS file or create a view on the model to address this challenge.

edit** I am still investigating solutions. While I have experience importing MST into components, incorporating it into plain js/ts files is unfamiliar territory for me. In light of this, any direction or assistance provided would be highly valued.

Answer №1

My recommendation is to explore the benefits of utilizing CSSModules.

This tool covers various functionalities, including addressing the specific scenario you outlined

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

The Rtk query function does not generate endpoints

Having trouble with code splitting in RTK-query, it's not working for me and I can't figure out why App.jsx import React from "react"; import { Provider } from "react-redux"; import store, { persistor } from "store" ...

Event delegation will be ineffective when the target element is nested within another element

After receiving a recommendation from my colleagues on Stackoverflow (mplungjan, Michel), I implemented the event delegation pattern for a comment list. It has been working well and I am quite excited about this approach. However, I have encountered an iss ...

A guide to JavaScript: Fetching and Parsing JSON Data from an API

Hey there! I've been working on using this code snippet in my defult.js file to call an API, but I'm having trouble figuring out how to read the output. It always seems to end up in the last else part. function fetchDataDist(APPID, flag, call ...

What is the best way to securely store a sensitive Stripe key variable in an Angular application?

When implementing Stripe payment system in my Angular App, I often wonder about the security of storing the key directly in the code as shown below. Is this method secure enough or should I consider a more robust approach? var handler = (<any>windo ...

Harnessing the power of the map function in TypeScript

Here is a collection of objects: let pages = [{'Home': ['example 1', 'example 2', 'example 3']}, {'Services': ['example 1', 'example 2', 'example 3']}, {'Technologies&apos ...

Is there a way for me to retrieve the value nested within an object within another object from this Api response?

Hey there, I'm currently struggling to retrieve the value of faceit_elo from within the csgo object. I attempted using data.games.csgo.faceit_elo but unfortunately it didn't yield any results. Any suggestions on how to access this value would be ...

Passing Props in Material-UI v5xx with ReactJS: A Beginner's Guide

Struggling with the fact that useStyle() isn't functioning properly in my material-UI v5xx version, I found myself at a loss on how to pass props in this updated edition. In Material-UI v4, it was as simple as: const Navbar = () => { const [open ...

Leveraging API data within React: A step-by-step guide

I have a React application where I am making API calls. To manage these calls, I created a separate file called dataService.js to contain all the functions for interacting with the API. However, when trying to log the data in my component, I am getting a ...

Generating a collection of items using a pre-existing array of items

Struggling to create an array of objects based on another array of objects. I attempted to use flatMap and then reduce, but encountered an issue when I tried to collect multiple statuses in one object. Below is what I have attempted and the desired result ...

Creating a custom form validation within a modal window featuring tab navigation, all styled with the latest Bootstrap

Within a modal, I have incorporated a header with tabs and tab content in the body, following the structure of Bootstrap 5. The modal footer includes buttons separated by dots. When encapsulating the modal body and footer within a form tag for validation ...

Reducer is not a standalone function in the realm of React Native's Redux framework

I need to implement a reducer in my react native application. The store constant is defined as follows: export const USER_PROFILE = 'USER_PROFILE'; This is the content of action.js file: import {USER_PROFILE} from '../constants/index'; ...

The entered value in the <input> field is not valid

I am encountering an issue where the input value is auto-filled, but when I click the submit button, the input field value is not recognized unless I modify something in it, such as deleting and adding the last word to the first name. Is there a way to m ...

Requirements for Method Decorators - The complete path of the class module using the decorator must be provided

Upon running the decorator (method decorators) function, we are provided with access to target, methodName, and descriptor. I am seeking the module path for target in this specific scenario. Essentially, I want the file path that points to the module that ...

Unable to hide jQuery form and receiving undefined function output

I seem to be facing an issue with one of the buttons. It's not functioning properly. Whenever I click on the "Add Run" button followed by the "Home" button, most functions stop working as expected. The dynamically created form doesn't hide, the ...

Tips for capturing a jQuery trigger in traditional JavaScript

I am trying to trigger an event using jQuery and I want to bind to it in a non-jQuery script. It appears that while I can bind to the event in jQuery using on, I am unable to do so with addEventListener. Check out this jsFiddle for a demonstration: http: ...

What is the function of this.handleClick that is positioned on the LEFT side of the = operator?

I'm struggling to understand the usage of this in an ES6 constructor. Initially, I grasped the following concepts (see example below): - We utilize this.height = height; to introduce a new instance variable. - Adding a new instance method with cl ...

Tips for ensuring that the code inside a subscribe block completes before moving on to the next iteration within a forEach loop in Angular

Within the code snippet below, there exists a for loop where an API call is made. The intention is to have the 1st API call complete and execute all the subscribed code before moving on to the next iteration of the loop, triggering another API call. Curre ...

A method to ensure that inline <div> elements occupy the entire available width

The typical solution for this issue is using float, however, it does not work in my situation. I attempted to utilize flexbox and overflow:hidden for the parent element, but unfortunately, it did not resolve the issue. Currently, I am dealing with three i ...

Enhance the responsiveness of full-screen pop-ups

My current project involves creating a full-screen pop-up for a specific application. /* Custom Full Screen Popup */ .fullscreen-popup { position: fixed; top: 0; ...

Selecting properties from a GeoJSON object on the fly with Leaflet

I am currently attempting to dynamically modify the displayed property on my leaflet map. Below is the code I have been working with: $("#button_thermal").click(function(){ $.getJSON("physicalProperties.geojson", function(data) { var geojson2 = L.geoJson( ...