Creating a Component Variation in Fractal

Posted on:

Tagged as: .

This confused me for a while as there seems to be a few ways to achieve this. In the end this is what worked for me.

First create your .hbs file and add your HTML:

<a href="button{{ extra_class }}">Button Label</a>

Note the addition of {{ extra_class }}, this will be where the difference in variants will be displayed.

Then create a config.yml file and add the following:

context:
  extra_class: 
variants:
  - name: highlight
    context:
      extra_class: ' button--highlight'

This will add the variation of Highlight to the sidebar when viewing in a browser, you should now see a Default and a Highlight. In the Highlight variant the value of extra_class will be added. Indentation in the .yml file is important, you will get errors if it’s not correct. I like to add all of the key value pairs to the default entry in the .yml file so I can see at a glance what I’ve got in the component.

If you want to change the name of the Default variant you can add a name: new-name-here to the top of the .yml file.

name: new-name-here
context:
  extra_class: 
variants:
  - name: highlight
    context:
      extra_class: ' button--highlight'

Ideally you wouldn’t include the button label text in the .hbs file, it would be cleaner to include it in the config.yml file. Your files would then look like this:

<a href="button{{ extra_class }}">{{ button_label }}</a>
context:
  button_label: Button Label
  extra_class: 
variants:
  - name: highlight
    context:
      extra_class: ' button--highlight'

You only need to include the button_label in the main version context, as we’re not changing the value all other variants will use this by default.

This is a very basic component, I encourage you to read up on the templating tags that can be used for more features.