Skip to content

Interacting with components in vanilla JS

Third-party services often provide JavaScript SDKs for building integrations.
In such situations, it can be useful to access Magewire components with vanilla JavaScript.

When a Magewire component is present on a page, the global Magewire variable is set on the window. It is the main way to interact with any Magewire component on the page.

Place code that uses the Magewire variable in a magewire:load event listener callback to ensure the Magewire property is set before your code is executed.

document.addEventListener('magewire:load', () => {
  // custom code using window.Magewire
})

Getting components in vanilla JS

The Magewire.find() method gives access to the JavaScript representation of a Magewire component.

Magewire.find('the.layout.block.name');

If Magewire.find('the-component-name') triggers the error

Uncaught TypeError: Cannot read properties of undefined (reading '$wire')

it means that there is no Magewire component with the specified name on the page.

At the time of writing, the best way to check if a component exists on the page is to check for an element with the given wire:id attribute.

// Ensure Magewire is initialized
document.addEventListener('magewire:load', () => {

  // Check if given component is present on the page
  if (document.querySelectorAll('[wire\\:id=entangle-example]')) {

    // Fetch component instance
    const myComponent = Magewire.find('entangle-example');

    // Do something with the component
  }
})

Reading properties in vanilla JS

To access the current value of component properties use the get() method:

// Read the property with the name "config"
Magewire.find('the.layout.block.name').get('config')

Reading a property value will not trigger an Ajax request.

Writing properties in vanilla JS

Updating a property can be done with the set() method:

// Set the property "foo" to the value "bar"
Magewire.find('the.layout.block.name').set('foo', 'bar')

This is equivalent to using the $set('foo', 'bar') magic action.

Setting a property value will trigger an Ajax request to synchronize the new value with the backend and re-render the component if needed.

Calling methods in vanilla JS

There are two ways to call PHP methods on components using vanilla JavaScript.
Methods can be executed either by simply calling them on the JavaScript component instance, or by passing the method name to call().

// Both of the following expressions call the method "navigateToStep" with one argument "payment"

Magewire.find('hyva-checkout-main').call('navigateToStep', 'payment')

Magewire.find('hyva-checkout-main').navigateToStep('payment')

Since emit and emitTo are available as public methods on all components, they can be called in the same manner.