mkfizi's avatar

Blade components best practice

I want to create typography component so my element will have class names consistency.

Which of the following method is best practice for creating anonymous blade components?

Method One

Directory

Components/
|--text.blade.php

text.blade.php

@props([
  'size' => 'sm'
)]

@php
  switch ($size) {
    case 'lg':
      $fontSize = 'text-lg';
      break;
    case 'md':
      $fontSize = 'text-md';
      break;
    case 'sm':
    default:
      $fontSize = 'text-sm';
      break;
  }
@endphp

<p {{
    $attributes->class([
        $fontSize, 
    ]) 
}}>
  {{ $slot }}
</p>

Usage

<x-text>Small Text</x-text>
<x-text size="sm">Small Text</x-text>
<x-text size="md">Medium Text</x-text>
<x-text size="lg">Large Text</x-text>

Method Two

Directory

Components/
|--text-sm.blade.php
|--text-md.blade.php
|--text-lg.blade.php

text-sm.blade.php

<p {{
    $attributes->class([
        'text-sm', 
    ]) 
}}>
  {{ $slot }}
</p>

text-md.blade.php

<p {{
    $attributes->class([
        'text-md', 
    ]) 
}}>
  {{ $slot }}
</p>

text-lg.blade.php

<p {{
    $attributes->class([
        'text-lg', 
    ]) 
}}>
  {{ $slot }}
</p>

Usage

<x-text-sm>Small Text</x-text-sm>
<x-text-md>Medium Text</x-text-md>
<x-text-lg>Large Text</x-text-lg>

Personally I prefer Method One since it allows dynamic usage and Method Two defines the same thing multiple times. However, Method Two is straight forward hence easy to maintain. What are your thoughts?

0 likes
1 reply
vincent15000's avatar

I think that both methods are good, it really depends on what you need.

Please or to participate in this conversation.