Use css/scss variable in React component as inline style
Asked Answered
H

2

7

Is there a valid way to use SCSS or CSS variable in React component as inline style?

I would like to do something like this below

scss

$red: #F65959;


:root {
  --red: $red;    
}

js

const style = {
  color: '--red',
};

export default style;
Halibut answered 13/3, 2019 at 13:25 Comment(0)
C
7

It should be like this if you want to use css custom properties

:root {
  --red: #{$red};
}
const style = {
  color: 'var(--red)',
};
Chambless answered 13/3, 2019 at 13:29 Comment(0)
R
2

It is working, but you need to give the variable to var() if you want to use it in the inlined styles.

Example

function App() {
  const style = {
    color: "var(--red)"
  };
  return <div style={style}>Foo</div>;
}

ReactDOM.render(<App />, document.getElementById("root"));
:root {
  --red: #F65959;    
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>

<div id="root"></div>
Rosarosabel answered 13/3, 2019 at 13:33 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.