Rengga Dev – In my recent “Custom Properties as State” post, one of the things I mentioned was that theoretically, UI libraries, like React and Vue, could automatically map the state they manage over to CSS Custom Properties so we could use that state right there if we wanted.
Someone should make a
useStateWithCustomProperties
hook or something to do that. #freeidea
Andrew Bloyce took me up on that idea.
It works just like I had hoped. The hook returns a component that is the Custom Property “boundary” and any state you pass it is mapped to those custom properties. Basic demo:
<div id="root"></div>
body { height: 100vh; margin: 0; display: grid; place-items: center; } .box { max-width: 400px; color: white; background-color: var( --activeColor ); /* comes from useStateInCustomProperties */ }
import React, { useState } from "https://cdn.skypack.dev/react"; import ReactDOM from "https://cdn.skypack.dev/react-dom"; import useStateInCustomProperties from "https://cdn.skypack.dev/use-state-in-custom-properties"; const App = () => { const [activeColor, setActiveColor] = useState("red"); const CustomPropertiesWrapper = useStateInCustomProperties("box", { activeColor }); return ( <CustomPropertiesWrapper> <h1 class="is-size-4">Active Color: {activeColor}</h1> <button onClick={() => setActiveColor("red")}>Change to red</button>{" "} <button onClick={() => setActiveColor("blue")}>Change to blue</button> </CustomPropertiesWrapper> ); }; ReactDOM.render(<App />, document.getElementById("root"));
This is clever and useful already, but I’m tellin’ ya, this will be extremely useful should the concept of higher level custom properties land. The idea is that you could flip one custom property and have a whole block of styling change, which is is what we already enjoy with media queries and you know how useful those are.