In this lesson, we learn how the x-init
directive in Alpine JS lets us run a JavaScript expression once the component has initiated.
We see the nuances that allow us to trigger that code before Alpine performs initial DOM updates, or after these updates have been made.
the x-init directive lets you run a JavaScript expression when the component is initiated, but before Alpine JS has performed initial updates to the DOM. If you pass x-init's callback function, it will wait until the initial DOM updates are made before running.
<div x-data="{name: ''}" x-init="() => $refs.nameInput.focus()"> <label>Your name</label> <input x-ref="nameInput" type="text" x-model="name"> <p>Hi, my name is <span x-text="name || '_______________'"></span>!