Component communication with $dispatch using Alpine js

I have a product category drop down and optional input fields that need to show/hide depending on the category being selected. $dispatch works correctly but I’m not able to receive value in other component.

Selecting a category

<div x-data="productCategories">
    <select name="productCategory"
        class="mt-1 block w-full pl-3 pr-10 py-2 text-base border-gray-300 focus:outline-none focus:ring-indigo-500 focus:border-indigo-500 sm:text-sm rounded-md"
        required
        @change="$dispatch('attribute', { brand: $event.target[event.target.selectedIndex].dataset.brand })"> 
        <option></option>
        <template x-for="[id, value] in Object.entries(categories)" :key="id">
            <optgroup :label="id">
                <template x-for="category in Object.values(value)" :key="category">
                    <option x-text="category.name" :data-brand="category.brand"
                        :value="category.name"></option>
                </template>
            </optgroup>
        </template>
    </select>
</div>

productCategories stored like this:

categories: {
    "Family": [{
            "name": "Health & Beauty",
            "brand": true,
            "size": false
        },
        {
            "name": "Baby & Kids",
            "brand": true,
            "size": true
        }
....

Optional input field to be shown if the category has brand : true

<div x-data="{ brand: ''}">
                                    
    <div class="col-span-3 sm:col-span-2" x-show="???">
        <label for="productBrand" class="block text-sm font-medium text-gray-700">
            Brand
        </label>
        <div class="mt-1 flex rounded-md shadow-sm">
            <input type="text" name="productBrand"
                class="focus:ring-indigo-500 focus:border-indigo-500 flex-1 block w-full rounded-md sm:text-sm border-gray-300">
        </div>
    </div>

</div>

I’m not sure how the components can talk to each other in this scenario. Any guidance or feedback on the code would be much appreciated. The $dispatch works correctly but i’m unable to receive the attribute specific boolean in the x-show or the x-if in a template

Answer

I think something like this should get the data from the event and set it in the component’s state.

<div x-data="{ brand: ''}" @attribute.window="brand = $event.detail.brand">

You can then use x-show="brand"

Leave a Reply

Your email address will not be published. Required fields are marked *