Media query for React with typescript

Media query is important to support responsible design.

There are a couple of ways to do that with React.

  1. Write media query css
  2. Using react-responsive
  3. Using styled-media-query

I'm going to tell you how to use styled-media-query here.

Installing styled-components and styled-media-query

yarn add styled-components
yarn add styled-media-query

How to use them

card.ts
import React from "react";
import styled from "styled-components";
import media from "styled-media-query";

const SytledCard = styled.div`
  border: 1px solid #e0e0e0;
  border-radius: 2px 2px 2px 2px;
  display: block;
  height: 200px;
  width: 300px;
  padding: 20px;
  margin-right: auto;
  margin-left: auto;

  background-color: #fffdfd;
  ${media.lessThan("small")`
    height: 160px;
    width: 240px;
  `}
`;

const Card = () => {
  return <SytledCard>Hello</SytledCard>;
};

export default Card;

Also, you can see the sample code at the github repository.

The good part of them is that you can write styles for each components and do not need to write css files.


Written by Yasuhiro Ito
Software engineer

© 2021, Yasuhiro Ito