Stack your classes within template literals

Chris Nager
Mar 9, 2016 · 2 min read
Image for post
Image for post

The purpose of this article is to share a simple technique I use that involves template literals, a useful feature of ES2015+. Template literals allow you to write multi line strings enclosed in back ticks, eliminating the need to escape each line with a backslash or having to concatenate each line with +.

instead of:

Template literal multi line strings are much cleaner!

It gets better. You can use ${} to denote a placeholder for a JavaScript expression, such as a variable or function. You can use placeholders inside your template literals like this:

Two extremely useful UI libraries I use in many projects are React and Basscss. They play nicely together because Basscss’s single purpose classes make style declarations predictable and are especially useful when working with reusable components in React. The following technique doesn’t require React or Basscss as dependencies, but I’ll use them to illustrate my point.

Within my React components, I stack my CSS classes in a template literal. This gives me the added benefit of clearly defining my props- and logic-based styles with placeholders.

See this demo on CodePen.

Writing your classes in a multi line stack has a few advantages. It’s better organized and more readable than a long single line of many classes.

When working with git, the main advantage of multi line stacked classes is that you can see your changes by line and know exactly what classes have been added or removed.

If you find this technique useful, ❤ this article. If you have any thoughts on the subject, let me know in the comments or reach out to me on Twitter @chrisnager.

Welcome to a place where words matter. On Medium, smart voices and original ideas take center stage - with no ads in sight. Watch

Follow all the topics you care about, and we’ll deliver the best stories for you to your homepage and inbox. Explore

Get unlimited access to the best stories on Medium — and support writers while you’re at it. Just $5/month. Upgrade

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store