E
E
eugenedrvnk2020-10-20 00:53:22
css
eugenedrvnk, 2020-10-20 00:53:22

How to dynamically update values ​​in the styled-components theme?

In projects, I quite often use a css variable in the spirit of --space-unit, to which I set the following styles:

--space-unit: 10px;

  @media (max-width: 991px) {
    --space-unit: 7px;
  }
  
  @media (max-width: 991px) {
    --space-unit: 5px;
  }


And then I use it something like this: And accordingly, when the screen is reduced, the margin will also decrease. How can such a system be adequately implemented in styled-components? After all, there, basically, for various kinds of variables, they use not css-variables, but ordinary js objects that stick in ThemeProvider, but so far I can’t figure out how to adequately make it so that, for example, I asked in the topic: And further at different resolutions this value changed, as in the situation with the css change. Personally, I see 2 solutions here, it's either to write a function into which to pass some additional parameters with breakpoints and monitor all this, or just leave --space-unit in css, but put it in ThemeProvider :

margin-bottom: calc(20 * var(--space-unit))


const theme = {spaceUnit: 10}


const theme = {spaceUnit: 'var(--space-unit')}

Which option would be more appropriate? Or are there other normal practices in order not to use this approach?

Answer the question

In order to leave comments, you need to log in

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question