Define CSS Variable w/o Styled Components

Viewed 339

I would like to define or update a CSS variable in React. I have seen numerous examples of this using the Styled Components library. Is there a way to set a CSS variable in React without something like Styled Components?

An example would be to update the definition each time state changes

useEffect( () => {
    // update css variable
    // --my-css-var: width 75%
}, [state])
2 Answers

Looks like this can be accomplished with style.setProperty() Docs

In React this would require the use of ref Docs so we can apply this to a particular element.

const reference = useRef(null);
const [state, setState] = useState(100);
useEffect(() => {
    reference.current.style.setProperty('--my-css-var', state);
}, [state]);

Yes, you can easily set the style. This is an example of setting the style with a function. After one second, the font color is changed.

function App(){

  function CanvasStyle(props){
    const [a_color,setColor] = React.useState(props.a_color);
    React.useEffect(() => {
      const timer = setTimeout(() => {
        setColor('blue')
      }, 1000);
      return () => clearTimeout(timer);
    }, []);  

    a_style = `
            body {
              color:`+a_color+`;
            }
            `;
    return(
        <>
            <style type="text/css">
            {a_style}
            </style>
        </>
        )
    }

return (
    <>
      <CanvasStyle a_color='red' />
      Hello World!
    </>
  )
}
Related