0

I need to add sass variable to styled components in react js ,I have go through this link Sass-extract-js and i have followed their procedure.

but i'm stuck in this line

import styled from 'styled-components';

const Button = styled.button`
background-color: ${p => p.theme.primary} //explain this line
`;

I have created var.scss file and contains

$black:#000000;
$white:#ffffff;
$red:#f64406;
$gray:#333333;
$green:#3bbd47;

In my render

<div>
  <div>
    <h2>Welcome Back!</h2>
    <h3>Login Your Account</h3>
  </div>

Styled component

const Content = styled.div`
 h1:${}//how i can get variable here
 `;
1
  • Why would you like to declare sass variables in order to use them in CSS-inJS in the first place ? Commented Sep 25, 2018 at 6:23

1 Answer 1

1

This can be achieved by using theming in the styled-components. You can add variables to ThemeProvider as follows:

const theme = {
black:#000000,
white:#ffffff
red:#f64406
gray:#333333,
green:#3bbd47
}
<ThemeProvider theme={theme} >
    <App />
</ThemeProvider>

and then this object can be used in the styled-components

const BlackDiv = styled`
  color: ${(props) => props.theme.black}`;

For more info please check theming

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

3 Comments

ok got it i need to import that constant variable theme file in index .js file right ?
but i did like this const theme = require(sass-extract-loader?{ "plugins": ["sass-extract-js"] }!./assets/css/var.scss);
You can use npm package npmjs.com/package/sass-vars-to-js to extract sass variable to js object

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.