DEV Community

yanir manor
yanir manor

Posted on

Control CSS using x-state state machines


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.


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


Congratulations we done.
The full code -
please run this line in terminal

npm run dev


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.

Top comments (0)