Alpinejs: x-text not updating text on conditional change

I have the following code which should, as far as I can see, update the text ‘Copy to Clipboard’ to ‘Copied!’ on the click of the element. The text is being copied to the clipboard, but the element isn’t changing it’s inner text. Any input would be appreciated.

<div x-data="{
        precopystore: 'Copy to Clipboard',
        postcopy: 'Copied!'
    }"
    class="flex flex-col items-center w-full md:min-w-[1/2] justify-center border-2 border-indigo-950 rounded-md">
        <div class="flex flex-col items-center justify-center py-2 text-indigo-950 font-semibold">
             {{ 'Text to be copied' }}
        </div>
        <div x-on:click="precopy = true; navigator.clipboard.writeText('Text to be copied');"
             x-init="precopy = false"
             x-text="precopy ? postcopy : precopystore"
             class="flex flex-col w-full items-center justify-center py-3 text-white bg-indigo-950 font-semibold cursor-pointer">
        </div>
</div>

The problem lies in the precopy variable. The way you use it, it results in a global variable (window.precopy) and by default the only variables watched must be defined in the Alpine object.

The solution is to declare precopy in x-data while x-init can be removed:

<div x-data="{
        precopystore: 'Copy to Clipboard',
        postcopy: 'Copied!',
        precopy:false
    }"
    class="flex flex-col items-center w-full md:min-w-[1/2] justify-center border-2 border-indigo-950 rounded-md"
>

    <div class="flex flex-col items-center justify-center py-2 text-indigo-950 font-semibold">
         {{ 'Text to be copied' }}
    </div>

    <div x-on:click="precopy = true; navigator.clipboard.writeText('Text to be copied');"
         x-text="precopy ? postcopy : precopystore"
         class="flex flex-col w-full items-center justify-center py-3 text-white bg-indigo-950 font-semibold cursor-pointer">
    </div>

</div>

Leave a Comment