Understanding how to use Sass maps

in Front-End Development

Recently I have been taking a dive into learning about Sass maps and how you can use them in our current projects. To make our front-end solutions more scalable, we can use Sass maps to keep our variables scoped similar to an object.

In this post I'd like to go through the basics of Sass maps and how to access values that are stored within one. I will also be going through how to loop through a sass map and how to go more than one level deep in a Sass map.

How to use a Sass map

Sass maps to me look like a JavaScript object from the way they are written. For example:

$Awesome-Map: (
   mapProp: 16px
);

If we needed to get mapProp from $Awesome-Maps then we would have to use the map-get method to access the property value.

.element {
  font-size: map-get($Awesome-Map, mapProp); // Returns 16px;
}

How to check if a map exists

If you want to add some form of validation to check if a map has a key then you can use the map-has-key method to check if the key exists in your map.

.element {
   @if(map-has-key($Awesome-Map, mapProp)) { // returns true
      font-size: map-get($Awesome-Map, mapProp);
   } @else {
      @warn 'Property does not exist within $Awesome-Map';
   }
}

If your property is wrong you will get a warning in your console which will help debug the issue.

Applying maps within maps

As we have learnt in the last sections we can use the map-get method to get the key value of a property. If you wanted to go down two levels or even three you can do this:

Setup:

$Awesome-Map: (
   childMap: (
      myProp: 16px
   )
);

Implementation:

.element {
   font-size: map-get(map-get($Awesome-Map, childMap), myProp); 
   // returns 16px
}

This looks very messy because we are repeating ourselves using the map-get to go deeper. Another method you can follow is a map-deep-get function which will loop through each level on the map to find the key you need.

Setup:

@function map-deep-get($map, $keys...) { 
  @each $key in $keys {
    // The first time the key will equal ChildMap 
    // Then it will finish on $myProp
    $map: map-get($map, $key); 
  }

  @return $map; // Returns 16px
}

Implementation:

$Awesome-Map: (
   childMap: (
      myProp: 16px
   )
);

// Without `map-deep-get`
$fontSize: map-get(map-get($Awesome-Map, childMap), myProp);

// With `map-deep-get`
$fontSize: map-deep-get($Awesome-Map, childMap, myProp);

Conclusion

I think Sass maps are very useful to use. If you need to make a colour theme, breakpoints or component settings config then using Sass maps would be very useful for you to use because it makes your code more modular and scalable.

Feel free to copy my example and have a play around with it.

CodePen Example: http://codepen.io/mattclaffey/pen/PNZgEo

Editor: http://www.sassmeister.com/

Share on Twitter