how do I use the getPropertyValue and setPropertyValue methods on a React ref.current without using findDomNode

138 Views Asked by At

so if I have a react ref and I attach it my element

const buttonRef = useRef();
return(
    <div className="box">
      <h1>The Button has a ref</h1>  
      <button
        onClick={toggleColor}
        ref={buttonRef}
        className="button">
          Special Button
       </button>
    </div>
  );

and my toggleColor method has the following code

const el = buttonRef.current;
const currentColor = el.getPropertyValue('--buttonColor');

but buttonRef.current does not have getPropertyValue, and of course not having the getPropertyValue method it does not have the setPropertyValue method.

I want to have some way to get a hold of the underlying dom element that does not use findDomNode as that is deprecated so that I can access the getPropertyValue and setPropertyValue methods of the element.

How does one do this?

Note the question does not ask how I get the value from window.getComputedStyles or anything like that. I want access to the element that ref.current is a reference to so that I have access to the methods available on that element.

1

There are 1 best solutions below

0
On

Ok well basically two problems were here in my misunderstanding - so first where I say el.getPropertyValue it should be

const style =  window.getComputedStyle(el);
const currentColor = style.getPropertyValue('--buttonColor')

Now as was noted in my question I expected that setPropertyValue should be on the same object as getPropertyValue, but that won't work because getComputedStyle is a read only object, so when I want to do setPropertyValue I had to do something like

el.style.setProperty('--buttonColor', newColor);

where newColor is a variable the value of which is derived by whatever logic you like.