Is it possible to retrieve stored colors from the Back End and incorporate them into an SCSS file?

Currently, I am in the process of restructuring my code to make it more clear and easier to maintain. I have a concept in mind, but I am struggling with how to implement it effectively. To enhance cleanliness and efficiency, I plan to create a separate _colors.scss file to house all the colors for the application. Essentially, it would look like this:


$colorPrimary: branding.colorPrimary,
$colorSecondary: branding.colorSecondary
...
Currently, the color styling is cluttered at the component level, and I want to organize it differently. For example:

<button style={
   color: branding.colorPrimary,
   background: branding.colorSecondary>
Hello
</button>

The colors are managed on the backend, so if I need to modify them, I have to make a call. I would greatly appreciate any assistance with tackling this challenge. Thank you.

Answer №1

If you want to achieve this functionality, there are two main approaches you can take. The first method mentioned is not compatible with Internet Explorer.

With the latest version of CSS outlined on the W3C website, variables can now be directly incorporated into CSS.

For instance, a backend can implement something similar to:

<head>
    <style type="text/css">
        :root {
          --primary-color: #cecece;
          --secondary-color: #fefefe;
        }
    </style>
</head>

Subsequently, in your scss (or css) file, you can use:

.mySelector {
   color: var(--primary-color, black);
}

This code snippet will essentially render as:

.mySelector {
    color: #cecece;
}

The color will fallback to `black` if `--primary-color` is undefined.

By utilizing these methods, it becomes easy for the backend to configure settings for the frontend. Meanwhile, from the frontend perspective, existing tools in the CSS API can be easily utilized.


However, if compatibility with IE is necessary, a more intricate infrastructure may be required.

The objective is to trigger webpack sass compilation every time a user changes their color selection, resulting in a generated css output with the relevant variable configurations.

To accomplish this, the use of Sass resource loader would be essential, automatically injecting sass files into all other files, akin to adding `@import "_colors"` automatically.

Following this, the backend server would need to:

  1. Create an _color.scss file at a specified location, e.g. /user/123/_color.scss
  2. Request compilation using `webpack client 123`
  3. Check the output webpack folder for client 123 and verify the presence of specific CSS files
  4. Inject them into the head section of HTML

In terms of webpack configuration,

Your webpack setup might include:

   const argv = require("yargs").argv;
    entry: {
        [...]
    },
    output: {
      // Use the argument as clientId to create a dedicated output folder
      path: helpers.root(`public/themes/front/${argv.client}`), 
      filename: "[name].[contenthash].js",
      chunkFilename: "[name].[contenthash].js"
    }

This way, based on the client id provided, the resulting CSS will be stored in a specific directory.

Finally, the SaSS rules could look like this:

 {
      test: /\.scss$/,
      use: [
        'style-loader',
        'css-loader',
        'postcss-loader',
        'sass-loader',
        {
          loader: 'sass-resources-loader',
          options: {
            resources: (argv.client) ? `/user/${ argv.client }/_color.scss` : `/user/default/_color.scss`,
          },
        },
      ],
    }

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

Stop the stacking of 'display:table' specifically on Android devices

I have created a social media menu with several different links. It displays correctly in Chrome, Safari, Firefox, and Internet Explorer on iOS devices, but on Android devices, the icons stack horizontally: Here is the HTML code: <ul id="menu-social"& ...

Customizing #app CSS with Vuetify for development and production environments

After developing my app using vuetify and vue cli, everything was running smoothly in the development environment. However, upon running npm run build, a new default #app CSS was generated and it ended up overriding my custom CSS in the final bundled file. ...

Utilizing jQuery to accentuate a specific div element when it is positioned directly in the center of the browser window

I have multiple divs with id="scroll_1", "scroll_2", "scroll_3", and so on. I am trying to implement a feature where when any of these divs is in the center of the window, I want to change the background color using jQuery highlight. Currently, I am able t ...

Finding a nested HTML element within a frame using Selenium without the presence of an iframe

Currently, I am delving into the world of Selenium using python to automate form filling on a particular website. However, my efforts have hit a roadblock as I am struggling to identify any elements within a frame and encountering a dreaded NoSuchElementEx ...

Having trouble showing the individual data retrieved from the API in React-JS

I'm having trouble showcasing the necessary information from an API response on the frontend. The API fetch code is as follows: async function obtainNFTData(){ const answer = await fetch(`https://api.rarible.org/v0.1/items/${chain}:${address}:${Id ...

Place a circular grid at the center of a webpage

Is there a way to align this grid in the center of a webpage? It appears skewed on mobile view but not on larger screens. The issue seems to be primarily with mobile devices. For instance, when viewed on a mobile device, the circles are positioned to the r ...

Tips for customizing the background of form inputs in React-Bootstrap

Currently, I have a next.js project with react-bootstrap. I am attempting to change the default blueish gray background color (#e8f0fe or rgb(232, 240, 254)) that bootstrap uses for form inputs to white. To achieve this, I am customizing the bootstrap var ...

How can you make an IonPopover dynamically appear from a button with the perfect positioning?

I want to display a popover below a button when the button is clicked, similar to the example on the Ion docs page. However, I am having trouble implementing this in React as the code provided is only for Angular. Here is my current code: ... <IonButt ...

Update the file path in the asset-manifest.json file

For my experiment with Azure DevOps, I decided to work on a ReactJS project that I found at https://github.com/alik0211/pokedex. The project runs smoothly when I build it locally and use npm start in the build folder. One of the files is located at http:// ...

Pictures fail to display following deployment

After coding my app in react js and successfully displaying images on the local server, I encountered a problem when deploying the app on Netlify - the images disappeared. <Card.Img variant="top" src="src/images/leo-self.jpg" class ...

Using a combination of CSS selector, several attributes, and the OR operator

Can you assist me with CSS selectors? Let's say we have a style HTML tag: <style type="text/css"> [...selector...] {color:red;} </style> I want to create a selector with multiple attributes and logical operators, but I am uncertain about ...

Error: The property 'hash' cannot be read from a null value in webpack

I've been facing issues while trying to build my nextjs project. Everything works smoothly during development, but encounters errors during the build process. I attempted to solve the issue by deleting the node_modules directory and reinstalling the p ...

Is it possible for me to transform a React Component reference into JSON format?

Is it possible to convert the state of a React component into JSON format, store it in a database, retrieve it later as JSON, and then convert it back into a valid state? My current code snippet is as follows: const [exampleState, setExampleState] = useSta ...

Verify if the React application is currently operational within a Docker container

When it comes to Node servers, I can easily determine if they are operating in a Docker container by utilizing the is-docker package. However, this approach does not apply to React applications that run within the browser environment rather than through ...

Unable to adjust the padding of the material UI Select component

I'm having trouble adjusting the padding of the Select component in order to align it with the size of my other text fields. Despite knowing that I need to make changes to nested components, I have yet to discover a viable solution. <div className ...

Print page headers are being overlapped by THEAD elements

I have created a table and am considering using the thead as page headers if the table spans multiple pages. However, I am encountering an issue where the content of the table overlaps with the table header on the second page. Here is a snippet of my HTML ...

When utilizing Spacemacs, npm run encounters a crash

Upon launching my react server, I encountered an error while trying to edit a file using spacemacs. The specific error message reads as follows: Error: ENOENT: no such file or directory, stat '/home/bitvivaz/Documents/tutorials/Website Development/re ...

Struggling to get the font-weights of the Typography and Button components in the new React with Material-UI to display

In both my previous and most recent React applications, I have the following code snippets: <Typography variant="h6" color="inherit" noWrap > h6. Heading </Typography> <Button type="button" size="large" color="primary" > ...

Error encountered due to unidentified JSX syntax within div element

**** When I check the terminal, this is what I see **** ./src/card.js Line 9:9: Parsing error: Unterminated JSX contents 7 | <h2>john doe</h2> 8 | <p><a href="/cdn-cgi/l/email-protection" cl ...

Transmit image file location from Node.js Express server to React client

My goal is to create an API that can store images and then send them to a React client application. The images are currently located within the Express app in the public/images folder. I would like to send a data object to the client with the image path ...