3

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
  • Did you mean override a css class? Commented Mar 13, 2021 at 20:55
  • Can you please elaborate? Also what have you tried yet? Commented Mar 13, 2021 at 20:56

2 Answers 2

1

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]);
Sign up to request clarification or add additional context in comments.

Comments

0

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!
    </>
  )
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.