Using the section :export in the SCSS :root declaration

In the file test.module.scss, I store all my variables for colors, typography, and more. I want to be able to use these variables in my react components. However, the file starts with :root to define the variables:

:root{
  --color-white: #fff;
  --color-black: #000;
  //...more colors
}

I have tried adding :export in different ways to make the variables accessible in my react component:

:root{
  :export{
     --color-white: #fff;
     --color-black: #000;
     //...more colors
  }
}

or

 :export{
      :root{
         --color-white: #fff;
         --color-black: #000;
         //...more colors
      }
    }

or even:

:root:export{
    :root{
       --color-white: #fff;
       --color-black: #000;
       //...more colors
     }
}

However, none of these approaches work as expected. The variables are either not accessible from react components or not exportable. Is there a way to properly export these variables without duplicating them at the end of the file?

Answer №1

I implemented a method similar to this:

Create a separate .modules.scss file to define the colors and eliminate any dashes to ensure the variables function effectively in JavaScript.

colors.module.scss:


@function str-replace($string, $search, $replace: '') {
  $index: str-index($string, $search);
  @if $index {
    @return str-slice($string, 1, $index - 1) + $replace + str-replace(str-slice($string, $index + str-length($search)), $search, $replace);
  }
  @return $string;
}

$colors: (
  color-primary: #4EB96C,
  color-accent: #EF5B27,
  color-neutral: #29324E,

  ... (color variables continue)

:export {
  @each $key, $value in $colors { #{str-replace($key, "-", "")}: #{$value}; }
}

Import the original variables in _variables.scss and iterate through them to export each one.

_variables.scss:


@import 'colors.module.scss';

:root {
  @each $name, $value in $colors {
    --#{$name}: #{$value};
  }
}

Utilize the variables in JavaScript:

file.js:


import colors from "src/styles/config/colors.module.scss";

console.log(colors.gray25) 
//#FCFCFD

Utilize the variables in SCSS:

style.module.scss:

.selector {
    background-color: var(--gray-25);
}

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

Tips for incorporating JavaScript modules into non-module files

Learning how to use js modules as a beginner has been quite the challenge for me. I'm currently developing a basic web application that utilizes typescript and angular 2, both of which heavily rely on modules. The majority of my app's ts files ...

Is it possible to receive a unique value error even when providing the correct key value in a map?

I encountered an issue while using a map function with an array in my application. Even though I have provided a unique key, Google Chrome console is still showing an error related to the unique key. Error Each child in a list should have a unique "ke ...

powerful enhancer separates the heading into a layout

I have an HTML div element that just isn't behaving right when I resize the screen. The title pretty much sums it up: <div class='serveMessage'><strong>Fun fact:</strong>&nbsp;over 1,259,468 American students fail ev ...

The AJAX request was successful, however, the PHP script did not return any

When using an Ajax success function to alert data in JavaScript, there may be occasions where the PHP side shows that the GET array is empty. <script type="text/javascript"> var myArray={ name:"amr", age:22 } myArray =JSON.stringify(myA ...

Summon wicket from the non-wicket-component entity

I am currently utilizing js-lib to transform text into a rich-editor, complete with options such as "bold", "italic" and more. The RichEditor also includes an UploadImage button, for which I am able to modify the call-back function: function startUploadi ...

Tips for verifying the contents of a textbox with the help of a Bootstrap

I am still learning javascript and I want to make a banner appear if the textbox is empty, but it's not working. How can I use bootstrap banners to create an alert? <!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8&g ...

What is the proper way to execute a script and transmit arguments when the client is connected via a socket?

Is it possible to execute a script that passes arguments to a connected client using Socket.IO? Here's an example scenario: var io = require('socket.io').listen(http); io.sockets.on('connection', function (client) { console ...

Effectively handling server downtime with AngularJS $resource

I've implemented this code in my services.js file: angular.module('appServices', ['ngResource']). factory('User',function ($resource) { return $resource('http://localhost\\:3001/api/user/:id', { ...

create a recurring design wallpaper within the TinyMCE editor

One of my functions alters the background of the tinymce editor. However, I am interested in having a wallpaper repeat in a similar fashion to background-repeat: repeat; in CSS. How can I achieve this? Here is the function: function SettinymceImage(bg_i ...

Issue: Angular JS radio input not functioning as expected

Below is the code snippet in question: <div ng-controller="TestController"> <input ng-repeat="item in array" ng-model="selected.name" value="{{item.name}}" type="radio"></input> </div> <script type="text/javascript"> ...

Mapping the correct syntax to apply font styles from an object map to the map() function

React, JS, and Material UI Hey there, I have a question about my syntax within the style property of my map function. Am I missing something? Fonts.jsx export const fonts = [ { fontName: 'Abril', key: 'abril', fontFamily ...

Explaining the jQuery $.post method

After a thorough search, I finally discovered the importance of adding return false; at the end of my JQuery code for posting data. Without it, my code wasn't functioning as expected. As a beginner in JQuery, I would appreciate some insights into the ...

Navigating through the CSS menu located in the main directory

I am facing an issue with accessing my CSS menu in different directories. In my root directory, I have a CSS menu that I want to use in subdirectories as well. However, when I navigate to a subdirectory, I find it difficult to go back to the main directory ...

Ways to extract the coordinates for slices positioned around the circumference of a pie chart

Currently, I am working on designing a pie chart with D3 using d3.layout.pie(). The image resembles the one displayed below, but without the black dots. These dots were added manually in Photoshop to highlight an issue that I am facing. I am curious about ...

What is the proper way to search for a specific string within a JavaScript array during an iteration?

I am working with an array that is continuously updated with new string elements every 2 seconds. The code snippet below showcases how the updates are processed: //tick world setInterval(function(){ doTradeUpdate(); },5000); function doTradeUpdate(){ ...

What is the process for displaying the attributes of a custom object in Typescript?

I need help returning an array of prop: value pairs for a custom object using the myObject[stringProp] syntax. However, I keep encountering this error message: TS7053: Element implicitly has an 'any' type because expression of type 'str ...

Align elements vertically with React-Bootstrap by using the built-in functionality for center

Struggling to vertically center and center align elements using bootstrap, even with react-bootstrap col and row components. You can view my code on Codesandbox: Link Here is the code snippet: import React, { PureComponent } from "react"; impo ...

Stop HTML5 video playback when resizing the window

I am currently working on a responsive HTML banner that includes a video using the video tag. The entire unit scales with the window size, and I have set up a breakpoint to trigger new divs when the window width is below 820px. This is achieved with the fo ...

The webpage becomes unresponsive due to an Ajax request

Creating a generic way to call ajax requests on my webpage has been challenging. I've developed an extension method for calling post requests asynchronously. $.tiqPost = function(action,data,callback) { alert('Posting...'); $.fancyb ...

Tips on effectively utilizing dynamic data with Google Charts

I am working on creating a dynamic chart using Google Charts with multiple CSV files. I want to display a different chart depending on the selection made by the user. The first file loads successfully and displays a chart, but the $("#selection").change(.. ...