First, you need to have TailwindCSS already setup with Laravel. To do so, you can follow the official documentation at TailwindCSS.
Since TailwindCSS requires classes to be present in whatever file you have specified inside your content
array in tailwindcss.config.js
, during your development you might experience missing styles due to the usage of variables inside your *.blade.php
files (for example).
Consider the following case, you have few buttons that look exactly the same except for their background color:
1
2
3
4
5
6
7
8
<!-- button for default operations: eg. login -->
<button type="button" class="bg-blue-700 hover:bg-blue-800 focus:ring-blue-300 focus:ring-4 text-white font-medium rounded-lg text-sm px-5 py-2.5 mr-2 mb-2">Default</button>
<!-- button for potentially dangerous operations: eg. disabling 2FA -->
<button type="button" class="bg-orange-700 hover:bg-orange-800 focus:orange-orange-300 focus:ring-4 text-white font-medium rounded-lg text-sm px-5 py-2.5 mr-2 mb-2">Warning</button>
<!-- button for dangerous operations: eg. deleting -->
<button type="button" class="bg-red-700 hover:bg-red-800 focus:ring-red-300 focus:ring-4 text-white font-medium rounded-lg text-sm px-5 py-2.5 mr-2 mb-2">Danger</button>
What changes in each button is the css utility classes applied for background color. Now since the markup is the same and the styling for text also matches each button, let’s create an Anonymous Blade Component button:
1
2
3
4
5
6
// ./resources/views/components/button.blade.php
@props(['color' => 'blue'])
<button type="button" class="bg-{$color}-700 hover:bg-{$color}-800 focus:ring-{$color}-300 focus:ring-4 text-white font-medium rounded-lg text-sm px-5 py-2.5 mr-2 mb-2">
{{$slot}}
</button>
And use it in our view as follows:
1
<x-button color="blue"> Default </x-button>
However, since the class names use php variable (bg-{$color}-700
), TailwindCSS isn’t able to extract them (don’t forget to run npm run watch
/ npm run dev
) and your buttons won’t look as expected (almost invisible, white text on white background yikes).
To solve this, let’s create several new components, representing the state of our button and one base component containing the common styles between them, in a new folder at views/components/button
:
1
2
3
4
// ./resources/views/components/button/base.blade.php
<button type="button" {{$attributes->merge([class="text-white font-medium rounded-lg text-sm px-5 py-2.5 mr-2 mb-2"])}}>
{{$slot}}
</button>
Now let’s create the default “state” of our button:
1
2
3
4
// ./resources/views/components/button/default.blade.php
<x-button.base class="bg-blue-700 hover:bg-blue-800">
{{$slot}}
</x-button.base>
And we can use the Default
button in our views as follows:
1
<x-button.default>Default</x-button>
If you run npm run dev
, you will see that the button now have background color, you can do the same thing for all button states that you have and tailwindcss will be able to extract those classes with no problem.
Stay humble,
Iv