Componentizing a Framework

Avatar of Chris Coyier
Chris Coyier on

DigitalOcean provides cloud products for every stage of your journey. Get started with $200 in free credit!

I’m sure most of you understand how you work with a framework like Bootstrap, Foundation, or Materialize. You use their CSS and JavaScript. You also use their chunks of HTML, piecing together and applying classes as needed to do what you need to do.

You’re on your own piecing the HTML together. That’s good, because it’s flexible. People use frameworks like this in all kinds of CMS’s and backend systems. But what if you want to apply some structure to this, making actual components out of the components given to you in the framework?

That’s exactly what Morgan Feeney did in Component-Led Design Patterns with Nunjucks & Grunt last year.

For example, Bootstrap gives you some HTML for alert messages, that are like this:”

<div class="alert alert-success" role="alert">...</div>
<div class="alert alert-info" role="alert">...</div>
<div class="alert alert-warning" role="alert">...</div>
<div class="alert alert-danger" role="alert">...</div>

We could abstract that into a reusable component by:

  1. Pass in the type of alert (second half of the second class)
  2. Pass in the content inside the alert

I’m sure you could imagine doing that in the backend or templating language of your choice. A single PHP file in which you set variables representing those things before you include it. A Rails partial in which you pass locals to it. A literal React component in JSX where you pass the stuff as props. This kind of thing makes these patterns a lot easier to reuse.

Morgan did this with Nunjucks:

{% macro alert(class="success", text="<strong>Well done!</strong> You successfully read this important alert message.") %}
  <div class="alert alert-{{ class }}" role="alert">
    {{ text | safe }}
{% endmacro %}

I think this is super compelling and the kind of thing we’ll be doing more and more as design systems are becoming more of a standard practice.

I also think Nunjucks is pretty darn cool.

I ported Morgan’s idea (which is already a repo) over to a CodePen Project if you’d like to have a play there.