Sass Dynamic Media Queries using if/else and Mixins in React

·

2 min read

Sass Dynamic Media Queries using if/else and Mixins in React

Media queries are the basics required for building any responsive web design, while Sass is a preprocessor that helps reduce repetition while writing CSS in order to have cleaner code that is easier to maintain. This is done by introducing features such as variables, nested rules and mixins into regular CSS.

Sass mixins are blocks of code that can be defined once and re-used multiple times in your project. This leads to cleaner and more efficient code.

Using Mixins With Media Queries

This article assumes that the reader has the following:

  • Node >= 8.10 and npm >= 5.6 on your machine.

  • Basic knowledge of Html, SCSS, Javascript and React.

Start by creating a project by running :

npx create-react-app my-app
cd my-app
npm start

Install node-sass

npm install node-sass --save

Rename files from .css to .scss

change.png

Create a file for mixins

mixin.png

The mixins will be written based on the size of the viewport

@mixin bp($point) {

$mobile: "(max-width: 600px)";
$tablet: "(min-width: 601px) and (max-width: 900px)";
$desktop: "(min-width: 901px) and (max-width: 1200px)";

@if $point == mobile {
      @media #{$mobile} { @content; }
    }
      @else if $point == tablet {
        @media #{$tablet} { @content; }
    }
      @else if $point == desktop {
        @media #{$desktop} { @content; }
    }
}

The mixins can then be imported into and used in the .scss file as follows:

@import './mixins.scss';
body {
    padding: 10%;

    @include bp(mobile) {
        padding: 6%;  
    }

   @include bp(tablet) {
        padding: 11%;
    }

    @include bp(desktop) {
        padding: 14%;
    }
}

This will look like so in the .css file

body {
  padding: 10%;
}

@media (max-width: 600px) {
  body {
    padding: 10%;
  }
}

@media (max-width: 900px) {
  body {
    padding: 11%;
  }
}

@media (max-width: 1200px) {
  body {
    padding: 14%;
  }
}

You can also look through the Sass documentation on media queries and mixins . By using Sass mixins, we have one centralized location in which to manage our media queries.