8

I have the following tag with a hard-coded color:

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

I want to use a LESS variable that I've defined instead, let's called it @tertiary-col, how would I use this variable? <p style={{ color: '@tertiary-col' }}> doesn't seem to work

3
  • Is it scss/less variable or a native css variable? Commented Aug 21, 2018 at 10:28
  • <p style={{ color: tertiary-col }}> .. .but I dont think "tertiary-col" is a valid variable name Commented Aug 21, 2018 at 10:29
  • @shmotam hi yes sorry I meant LESS not CSS Commented Aug 21, 2018 at 10:40

3 Answers 3

8

It is possible to use native var() to do this.

By placing the variable in :root then it becomes available anywhere you need to use it.

You would do --tertiary-col: @tertiary-col;, but for the purposes of the snippet I have put in an actual hex value.

:root {
  --tertiary-col: @tertiary-col; /* this is what you would do */
  --tertiary-col: #646464; /* @tertiary-col; */
}
<p style="color: var(--tertiary-col)">Some text</p>

Here is an excellent tutorial on css variables: https://codepen.io/abcretrograde/full/xaKVNx/

Sign up to request clarification or add additional context in comments.

Comments

4

You cannot use variables from CSS-precompilers like LESS inside of your JSX. You can either use JavaScript variables like

const redColor = "#FF0000";

<p style={{ color: redColor }}

Or give it a className and let your CSS handle the rest.

Another option would be to add a loader like less-vars-to-js to map your LESS variables (I'm assuming you mean LESS as you're using @) to JavaScript.

And another option would be to use native CSS variables as other answers suggested, you can use these variables within your JavaScript, the downside on this is that they aren't supported by all browsers (yet).

2 Comments

You could AFAIK use a native CSS property color: --some-css-var on browsers that support it.
IE11 is the only browser that does not support @var.
1

For using native css variables in React:

Let's say you want to toggle between light and dark themes for any text nodes in a certain element:

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

Then, any parent can set that variable, and it effectively acts as context to any child element that explicitly chooses to use that specific CSS variable:

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

Reference

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.