eugenedrvnk
eugenedrvnk

Reputation: 493

How to update styled-components' variables depending on the media queries?

My theme is the following:

const theme = {color: red};

And I'm using this variable in components in this way:

const Button = styled.button`
  color: ${props => props.theme.color};
`;

And I want that if the screen width is less than 992, the color becomes green. How can I achieve this using styled components theming? Because, using css variables I can just do next:

:root {
  --color: red;
  
  @media (max-width: 991px) {
    --color: green;
  }
}

But in styled-components it's impossible. Just one way that I currently see is to set theme variables like this:

const theme = {color: var(--color)}

But in this situation I can't use this variable value in js. So, what can be the solution?

Upvotes: 0

Views: 290

Answers (1)

Andrew
Andrew

Reputation: 1252

You can use media queries with styled components in much the same way, so you if you had the two colours you wanted to use in your theme object, you would end up with something like

const Button = styled.button`
  color: ${props => props.theme.colorRed};
  @media (max-width: 991px) {
    color: ${props => props.theme.colorGreen};
  }
`;

Upvotes: 1

Related Questions