Schedule Input Focus with requestAnimationFrame to Handle Multiple DOM Mutations in Zag.js

Share this video with your friends

Send Tweet

We'll be implementing the backspace event which triggers two actions: clearFocusedValue, and focusPreviousInput.

These implementations you'll be familiar with at this point but what you'll notice when we actually try to hit backspace that the focus value will get cleared but we won't be setting focus to the previous input. This is because there are several DOM mutations happening at the same time. We'll fix this by scheduling the focus of inputs to the next animation frame with requestAnimationFrame

f1729
f1729
~ 2 years ago

Is a good practice to include logic that involves DOM manipulation inside the machine? I would think that the machina should only manipulate the state.

Segun Adebayo
Segun Adebayo(instructor)
~ 2 years ago

Yes, I would consider it a good practice since the machine will need to interact with the "outside world" at some point via its actions. In this case, we're interacting with the DOM. Actions and Activities in state machines are the best way to handle those.