Search code examples
cssreactjsmedia-queries

@media queries in a very odd React implementation using .tsx and .ts files


I have been working with React for the past two or so years, and with @media queries since the early 2000's. I have just been onboarded onto a new project where they are building React components in a fairly novel way, at least to my experience.

I'll place a snippet below to illustrate what I mean, but essentially they do not use .js and .css files as I usually do, but rather use .tsx and .ts files. They create a component in the .ts file and immediately apply the styling. It looks like this:

//.ts file

export const Container = styled.div`
  .second-chart {
    margin-top: 44px;
  }
`;

//.tsx file

import {Container} from "./styles";
...
<Container>
   <div className="second-chart">
   ...
   </div>
</Container>

I perfectly get how this works, and it seems simple enough to use. I am however concerned about how I would write @media queries for this type of implementation? I don't even know what to call it so I might be able to search for suggestions online.

Does anyone know a term I can use for this type of implementation? Or better yet, could someone please let me know how I can write a @media query for it? I was thinking that if I knew how to add a class to the 'styled.div' portion in the .ts file, I could always add my @media queries to a separate .css file.

Any advice would be greatly appreciated.


Solution

  • It looks as though the project is using Styled Components. As @phunder has pointed out, you can include all your normal css within the styled element which includes your media queries like so:

    export const Container = styled.div`
      font-size: 16px
    
      @media only screen and (max-width: 600px) {
        font-size: 12px
      }
    `;