Blog>
Snippets

Automating Breakpoints with Sass Mixins in Next.js

Explain how to create and use a mixin for handling media queries and breakpoints in Sass, providing a practical example within the context of a Next.js application to implement responsive design.
// mixins.scss
@mixin respond-to($breakpoint) {
  @if $breakpoint == 'phone' {
    @media (max-width: 599px) { @content; }
  } @else if $breakpoint == 'tablet' {
    @media (min-width: 600px) and (max-width: 899px) { @content; }
  } @else if $breakpoint == 'desktop' {
    @media (min-width: 900px) { @content; }
  }
}
This Sass mixin allows you to easily handle different breakpoints by passing the desired breakpoint as an argument. It uses media queries internally to apply the styles according to the screen size specified by the 'phone', 'tablet', or 'desktop' arguments.
// styles.scss
@import 'mixins'; // Make sure to import the mixins file

.my-component {
  font-size: 16px;

  @include respond-to('phone') {
    font-size: 14px;
  }

  @include respond-to('tablet') {
    font-size: 15px;
  }

  @include respond-to('desktop') {
    font-size: 16px;
  }
}
This is an example use of the 'respond-to' mixin in a Sass file where '.my-component' class is defined. It changes the font size of the component based on the screen size. The mixin is called with different breakpoints to apply the corresponding styles.
import styles from './styles.module.scss';

export default function MyComponent() {
  return (
    <div className={styles.myComponent}>
      Responsive text size!
    </div>
  );
}
In this JavaScript/JSX code for a Next.js component, we import the compiled CSS module from 'styles.module.scss' which includes our responsive '.my-component' class with different font sizes for phone, tablet, and desktop breakpoints. The styles are then applied to the 'MyComponent' functional component in Next.js.