Harnessing the Power of LESS Variables in React JS

Currently, I have a tag with a fixed color value:

<p style={{ color: '#646464' }}>

Instead of hard-coding the color, I want to utilize a LESS variable that I have set up, known as @tertiary-col. However, when I try using this variable like so:

<p style={{ color: '@tertiary-col' }}>
, it doesn't work as expected.

Answer №1

Utilizing the native var() function can achieve this.

When the variable is placed within :root, it becomes accessible wherever needed.

You can set it up like so: --tertiary-col: @tertiary-col;, but for demonstration purposes, a hex value has been provided in the snippet.

:root {
  --tertiary-col: @tertiary-col; /* method to define the variable */
  --tertiary-col: #646464; /* @tertiary-col; */
}
<p style="color: var(--tertiary-col)">Some text</p>

For those interested in learning more about css variables, check out this informative tutorial: https://codepen.io/abcretrograde/full/xaKVNx/

Answer №2

If you're looking to include variables from CSS-precompilers like LESS in your JSX, unfortunately that's not possible. Your options are to utilize JavaScript variables instead, such as:

const redColor = "#FF0000";

<p style={{ color: redColor }}

Alternatively, you can assign a className and let your CSS take care of the styling.

Another approach could involve incorporating a tool like less-vars-to-js to translate your LESS variables (assuming you're utilizing LESS given your use of @) into JavaScript.

Furthermore, consider leveraging native CSS variables as suggested by other responses. These variables can be accessed within your JavaScript, although it's worth noting that they may not be supported by all browsers at present.

Answer №3

To implement CSS variables natively in React:

Suppose you need to switch between light and dark themes for text elements within a specific container:

const LightDarkText = ({ children }) => (
  <span style={{
    color: 'var(--text-color, black)'
  }}>
    {children}
  </span>
);

Subsequently, any parent component can define that variable, which will then serve as context for any child element that opts to utilize the specified CSS variable:

// rendered
<div style={{
  backgroundColor: 'black',
  '--text-color': 'white'
}}>
  <article>
    <LightDarkText>testing</LightDarkText>
  </article>
</div>

Source

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

Having trouble with JavaScript not working when clicking an image and toggling a div?

Why isn't the onclick image and toggle div functionality working with JavaScript? I made the change from: <input type="button" id="Showdiv1" name="Showdiv1" value="Show Div 1" onclick="showDiv('div1')" /> to: <img src="https://d ...

Is there a way for THREE to load canvases asynchronously?

I have an artwork on a canvas that I want to transfer onto a texture similar to an image using ImageUtils. The challenge is that the canvas does not have an 'onfinished' rendering callback, so I have to rely on THREE for this functionality. While ...

Utilize Object.keys and Object.values to transform a JSON object into a ChartJS representation

I have a unique JSON file structure that I am trying to display in ChartJS. The data looks like this: { "AAPL": [ { "Q1": -26986, "Q2": -168099, "Q3": -137101, "Q4": -5 ...

Using CSS to style GLTF objects in THREE.js

Can CSS be applied to a GLTF model in THREE.js, such as setting transparency? Is it possible to achieve this with CSS styling rather than using JavaScript? For instance: <style> .transparency { opacity: 0.5; } </style> and then <a-asset- ...

What causes the error "Why is notify.js not being recognized as a function?"

Incorporating sources and links into my webpage, I included notify.js using the following code: <script src="/Scripts/jquery-3.5.1.js"></script> <script src="/Scripts/jquery-ui-1.12.1.js"></script> &l ...

What could be causing TypeScript to throw errors when attempting to utilize refs in React?

Currently, I am utilizing the ref to implement animations on scroll. const foo = () => { if (!ref.current) return; const rect = ref.current.getBoundingClientRect(); setAnimClass( rect.top >= 0 && rect.bottom <= window.i ...

How to delete a specific element from a JSON object using Node.js

I've been trying to figure out how to remove a specific ID from my ids.json file, but I can't seem to get it right. Here's the block of code that I've been working with: { "48515607821312": { "members": [ "23422 ...

Incorporate FontAwesome icons into table headers within an Angular framework

I am attempting to customize the icons for sorting in my table headers by following the guidelines laid out in the ng-bootstrap table tutorial. The NgbdSortableHeader directive plays a key role in changing the sorting of columns: @Directive({ selector: ...

How to access temporary file paths with JavaScript

Can anyone provide a method to retrieve the temporary file path of an uploaded file using <input type="file"/> and then send it to PHP through ajax, retrieve the file there, and save it? An explanation with code examples would be greatly appreciat ...

Tooltips experience issues when interacting with elements that do not utilize the :active state

$(function () { $('[data-toggle="tooltip"]').tooltip() }) <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" integrity="sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm" ...

What is the best way to ensure a navigation link stops scrolling at the bottom of a navbar that is set to position: sticky?

I am utilizing Bootstrap 5 for my website, and I have a sticky-top attribute on my navbar. When I click on one of the links in the navigation bar, the page scrolls to that section, but some of the content goes behind the navbar. I am looking for a way to m ...

I'm having trouble with my image links not working in Chrome, but they work fine in IE. What could be causing

My portfolio site has been successfully uploaded via FTP. However, I am facing an issue with the links in the 'latest work' section when viewed in Chrome. The first two links (Fine Art Site & Young Academy) function properly in Chrome, but the n ...

Generating a file with multiple lines and initiating the download using the Chrome.downloads.download function

On my client side, I am creating some content and trying to download it using chrome.downloads.download. However, when the file is downloaded, the new lines are missing. I am adding new lines in the code snippet below: lineContent += '\r\n& ...

Error Message: ASP.NET Razor Pages JavaScript file throws an undefined error

Trying to transition a website from Wordpress to ASP.NET Razor Pages and encountering some issues. After downloading files from the original site, including an 'assets' folder, a 'lib' folder (containing fonts, css, and js), and index. ...

Setting a defined width and using block display will not solve the issue of the margin:auto not working

rough sketch of my desired design I am trying to center a label on the page. The parent container is set to a width of 100% and the label itself is displayed as a block element with margin set to auto. When I set the width of the label to a smaller value, ...

An error occurred when saving data (date and time) retrieved from a different backend service into MongoDB

I am currently working on a project where I need to fetch JSON data from an external backend service and save it locally in my own database. The goal is to improve the loading speed of the data on the frontend, particularly for representing a graph. Here ...

Determining the position of a v-for element in Vue.js when making an HTTP request

I'm faced with a challenge involving an array of posts with comments, each post having an input for creating a new comment. The posts array contains the id of each post as a prop, but I'm unsure how to select the specific post for which I want to ...

Discovering the identification of a comment in JavaScript

Here is the code snippet I am working with: <a onclick="lel($(this),'212345555')" class="button"> <a onclick="lel($(this),'241214370')" class="button"> <a onclick="lel($(this),'248916550')" class="button"> & ...

Display a nested JSON object within a FlatList component

As a student diving into the world of React Native, I've been struggling for the past couple of days to display a specific part of a JSON response in a flatlist. Despite my efforts and extensive Google searches, I haven't made much progress yet. ...

Unable to locate a declaration file for the module "../constants/links" in src/constants/links.js, as it implicitly defaults to type 'any'

Within my VueJS application, I have brought in some constant variables. <script lang="ts"> import { Component, Prop, Vue } from 'vue-property-decorator' import { MOON_HOLDINGS_LINK, TWITTER_LINK } from '../constants/links' @Comp ...