Blog>
Snippets

Creating Modular Sass Components in Next.js

Show how to create reusable Sass components with partials and mixins in Next.js by structuring the styles directory, creating Sass partials, and importing them into component-level Sass files.
// 1. Inside your styles directory, create a partials directory
// _variables.scss
$primary-color: #5b3cc4;
// _mixins.scss
@mixin respond-to($media) {
  @content;
}
Create `_variables.scss` to store Sass variables like colors, fonts, etc., and `_mixins.scss` to store mixins like media query helpers. These files are placed in a `partials` directory within the `styles` directory.
// 2. Create a component-level Sass file, e.g., for a Button component
// Using the previously defined variables and mixins
// button.module.scss
@import 'partials/variables';
@import 'partials/mixins';

.button {
  background-color: $primary-color;
  @include respond-to('mobile') {
    padding: 0.5rem 1rem;
  }
}
Create a Sass file for a specific component, such as a button, and import the Sass partials (variables and mixins) to use them within this component's styles.
// 3. Import the component-level Sass file in your Next.js component
// ExampleComponent.js
import styles from './button.module.scss';

function ExampleButton() {
  return <button className={styles.button}>Click me</button>;
}
Inside a Next.js component, import the component-level Sass file and apply the styles to the HTML elements.