TALL Tales

How to Create Blade Heading Components with Tailwind

04 Oct, 2022

For me, as Tailwind is a utility based CSS framework, the most obvious use case is with Blade Components.

Blade Components are basically reusable pieces of code so that you can make a <h1> component and call it throughout your site but you then only need to edit it in one place should you choose to change the colour or font size for example.

One of the simplest components are the title tags - <h1> to <h6>. This tutorial takes you through how to set up and use them.

Register the Component

The first thing you need to do is to register the component, we'll start with the <h1> tag. In Terminal (or the CLI of your choice), run the following command:

	php artisan make:component h1

This will create two files, the first is the Blade Component file located in \resources\views\components and will be called h1.blade.php.

The second file will be a class for the view and this will be created in \App\View\Components and will be called h1.php.

Call the Component

So firstly we will change the tag in the containing Blade file (e.g. welcome.blade.php) from:

<h1>Users</h1> 
// to
<x-h1>Users</x-h1>

As we will see later we can add more details to this but for now we will keep it simple.

Format the Blade Component

In the new Blade Component file (h1.blade.php) we add in the code for the new tag:

<h1 {{ $attributes->merge(['class' => 'mb-0 pb-2 text-3xl font-medium']) }}>
	{{ $slot }}
</h1>

The $slot section is fairly obvious, this will show whatever is between the opening and closing tags. In our example this will be 'Users'.

The atrributes section will append any class you choose to add onto the <h1> tag in the containing Blade file to the base class we have defined above.

So, if I have this in my welcome.blade.php file:

<x-h1 class="underline">Users</x-h1>

the result will be:

<h1 class="mb-0 pb-2 text-3xl font-medium underline">Users</h1>

We can then create components for the other heading tags as well.

This example does not use the class file that was automatically created but that doesn't matter because we don't need it for this simple case. Later on we can create components that pass data through and these will need the class file as well.