Building components
3. Creating a button component
So you get the idea, inside the Components directory we create a new directory that matches the name of the component we want to create and then create a few files inside that directory. Let's repeat this process for the Button component.
Inside nitflex_dev_theme/src/components/ create a new directory called button.
Inside the button directory create a new file called button.json.
Inside
button.json
copy the following code:{ "button": { "text": "Watch now", "url": "", "type": "", "classes": "" } }
Inside the button directory create a new file called button.twig.
Inside
button.twig
copy the following code:{# If an url value is provided render as a link #} {% if button.url %} <a href="{{ button.url }}" class="button {{ modifier_class }}{{ classes|default('') }}"> {{ button.text }} </a> {# Otherwise render as a button. #} {% else %} <button type="{{ button.type|default('submit') }}" class="button {{ modifier_class }}{{ classes|default('') }}"> {{ button.text }} </button> {% endif %}
🔥 TIP
We've added some logic to the button to ensure we render the right HTML element based on the data we receive. For example, if we get a URL for the button, this means we need to render the button with an
<a>
tag so we can provide ahref
value. If no url is passed, we render an actual<button>
tag which means we will be performing an action rather than being direced to another page.Inside the button directory create a new file called button.scss.
Inside
button.scss
copy the following code:// Button // // This is the button component. // // Markup: button.twig // // Style guide: Components.Button // Import site utilities. @import '../../global/utils/init'; .button { background-color: $color-black; border: 2px solid $color-tundora; border-radius: 44px; color: $color-white; cursor: pointer; display: inline-block; font-size: 14px; font-weight: 600; padding: 14px 40px; text-decoration: none; transition: border 0.125s ease, background-color 0.125s ease; white-space: nowrap; &:hover, &:focus { border-color: $color-white; } }
Compiling the styleguide
Now that we have writen all the necessary code to build the Button component, it's time to see the component in the styleguide. Let's compile our project first.
- In your terminal or command line, navigate to
/themes/custom/nitflex_dev_theme
and run the following command:
lando npm run build
Viewing the Button component
Open your drupal site and point to the URL below
http://nitflex.lndo.site:8000/themes/custom/nitflex_dev_theme/dist/style-guide/index.html
Depending on your setup, you may not need to enter ":8000". Also if you did not use the provided Lando setup, ensure you are using your own custom URL.
Under the Components category you should see the new Button component.
Previous exercise: Creating a heading
Next exercise: Creating components variations