Sunday, May 12, 2024
48
rated 0 times [  53] [ 5]  / answers: 1 / hits: 55320  / 7 Years ago, wed, april 19, 2017, 12:00:00

I'm using styled-components to build my components. All style properties which accept custom values are reused throughout my components (as it should be). With that in mind, I'd like to use some sort of global variables so that updates will propagate to all components without needing to update each style individually.



Something like this:



// Variables.js

var fontSizeMedium = 16px;

// Section.js

const Section = styled.section`
font-size: ${fontSizeMedium};
`;

// Button.js

const Button = styled.button`
font-size: ${fontSizeMedium};
`;

// Label.js

const Label = styled.span`
font-size: ${fontSizeMedium};
`;


I guess I'm getting the syntax wrong though? Also, I know global variables are not recommended in Javascript land, but in design land reusing styles across components is an absolute must. What are the trade-offs here?


More From » styled-components

 Answers
110

I eventually figured this out, so here's how you can do it, at least if using React.



You need to define the variables in one file and export them.



// Variables.js

export const FONTSIZE_5 = '20px';


Then you need to import those variables into each component file.



// Button.js

import * as palette from './Variables.js';


Then you can use the variables in your styled-components like this:



const Button = styled.button`
font-size: ${palette.FONTSIZE_5};
`;

[#58088] Tuesday, April 18, 2017, 7 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
shawn

Total Points: 507
Total Questions: 103
Total Answers: 111

Location: American Samoa
Member since Fri, Aug 26, 2022
2 Years ago
;