Pass attributes / props as array

Viewed 526

I want to use an array and use it to fill the props of a laravel-blade (8.x) component dynamically. In short something like that:

<x-button size="sm" {{ $buttonProps }} /> where $buttonProps is an array with key-value pairs defining the props and its values for the button to render.

The array would look like this: ['label' => 'My Button', 'size' => 'sm', ...]

Here is a more in detail example of what I try to do:

1. Button component with some props
@props([
  'size' => 'md', # sm, md, lg
  'variant' => 'basic', # basic, success, error
  'label' => '',
])

@php
  // ... 
@endphp

<button {{ $attributes->merge([ 'class' => '...' ]) }}>
  {!! $label !!}
</button>
2. ButtonGroup - which will render the Buttons using an array for their props

Here is the thing which doesn't work: {{ $buttonProps }}. I want to dynamically pass down the props for the Button as an array. But this solution doesn't work like that of course. Is there a solution how I can do that?

@props([
  'buttons' => []
])

<div class="...">
  @foreach ($buttons as $buttonProps)
    <x-button size="sm" {{ $buttonProps }} />
  @endforeach
</div>
3. Finally how I would use the ButtonGroup in this scenario

You may notice that I pass some extra prop to the first button. That's basically why I need a dynamic approach as I don't know all the props passed in my real-life scenario.

<x-button-group
    :buttons="[
        [
            'label' => 'Export',
            'hello' => 'world',
            'type' => 'button',
            'onclick' => '() => alert(\'hello world\')',
        ],
        [
            'label' => 'Main action',
            'variant' => 'accent',
        ]
    ]"
/>

Note: I know I could easily make this example running using slots here, but my real-life example is a little different in requirements. I used Button and ButtonGroup as an example to illustrate my problem.

0 Answers
Related