DEV Community

yanir manor
yanir manor

Posted on

Control CSS using x-state state machines

Introduction

Do you ever think about adding a CSS condition to control a CSS behavior?
It will be hard and will include a lot of if statements most of the time.
Here is how you can control your styling through an x-state state machine.

Coding

First installing

npm install xstate @xstate/react

Let's build the machine. We'll design three possible states: idle, loading, and success.
To simulate, I added an automatic transition (this is the after with time in JSON).
Now that we have finished the machine, let's integrate it with the react code.
We will create a new data attribute called data-state.
This data attribute will contain the current state.
We are almost done, let's add CSS behavior.
you need to create CSS selector like this

.btn[data-state='loading']

Congratulations we done.
The full code -
https://stackblitz.com/edit/vitejs-vite-wjcxwo?file=src/App.jsx
please run this line in terminal

npm run dev

Conclusion

I like this approach.
I can design the state's behavior using x-state, then control it via CSS selector and assign the relevant attributes.
I think it gives a lot of power and simplicity to your styling ecosystem.

Hostinger image

Get n8n VPS hosting 3x cheaper than a cloud solution

Get fast, easy, secure n8n VPS hosting from $4.99/mo at Hostinger. Automate any workflow using a pre-installed n8n application and no-code customization.

Start now

Top comments (0)

Sentry image

See why 4M developers consider Sentry, “not bad.”

Fixing code doesn’t have to be the worst part of your day. Learn how Sentry can help.

Learn more

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay