Media queries in CSS in JS?

Hey guys, I’m having a bit of a trouble understanding how this matchMedia() function is supposed to work.

const white: string = '#FFFFFFF';
const lime: string = '#38C463';

const cellPhoneMediaQuery = window.matchMedia(
  '@media all and (min-width: 300px)'

if (cellPhoneMediaQuery.matches) {
} else {

export const formStyles = {
  textField: {
    fontFamily: 'Arial',
    color: lime,
  dropDown: {
    color: lime,
    backgroundColor: '#282C34',
  button: {
    color: lime,
    backgroundColor: '#24282E',
    padding: '10px 20px',
    fontWeight: 600,
  flexContainer: {
    display: 'flex',
    justifyContent: 'spaceBetween',

What are your ways to go about media queries in css in js?

I haven’t really used matchMedia much, but you likely want to use an event listener.

Not sure what the correct React way of using matchMedia is, but there might be some package to help with it. Here is a useMedia hook you can look at.

Ah, definitely. I’ve used the HOC from Material-UI and wrapped withStyles with a sizes file like so, just wasn’t sure if this was proper:

export default {
  up() {},
  down(size) {
    const sizes = {
      xs: "575.98px",
      sm: "767.98px",
      md: "991.98px",
      lg: "1199.98px",
      xl: "1600px"
    return `@media (max-width: ${sizes[size]})`;

Can’t really answer that.

I never got much into CSS in JS. I have played with it a little (Emotion, etc.) but I usually just use plain CSS.

I can see the benefits, but I do think it is one of the few weaknesses React has, unlike other frameworks like Vue, or Svelte where the CSS is inside the component and is scoped to the component. CSS in JS always felt a little offputting to me, but I’m guessing it is just a matter of using it enough.

The output (depending on the CSS in JS library) also can make it harder to debug the CSS, at least from what little I have seen, it can.

Believe me, I am absolutely not a fan of CSS in JS as well and only found good cases to use it (one being tracing SVG animations where the styles need to change on the fly). This is for a take-home, and I think the job application said they use CSS in JS, so I figured I’d throw it in.

Sounds like a good idea if the company is using some technology to show that you can learn and use it.

Good luck with the assignment.

Thanks a lot. I think I might just use a normal css file for media queries for fear of overabstraction. Do you know much of the React testing library / jest? Gotta write some basic tests for it and then I’ll be done I imagine.

No sorry, I know Jest a little but I never really did much React testing.

I’d definitely suggest checking out Kent C. Dodds and here is his YouTube channel. He does a lot of React testing stuff and is the author of the React Testing Library (React docs testing).

1 Like

No worries! Thanks so much for the help as always.