24

I'm trying to change background of a div when color value changes. Here is my function which receives color value:

ChangeColor(oColor) {
    this.props.ChangeColor(oColor);
    console.log("Refs: ", this.refs.colorPicker.className);
  },

Here is css class

.colorPicker {
    padding-right: 25px;
    background: #000;
    display: inline;
    margin-right: 5px;
  }

and here is my div element whose background needs to update on run-time.

<div ref='colorPicker' className={this.GetClass("colorPicker")}  />

I'm not sure about refs synatx so please help to fix this issue. Thanks.

Muhammad Ateeq Azam
  • 1,009
  • 1
  • 12
  • 26

3 Answers3

27

I found it. Here is answer:

  ChangeColor(oColor) {
    this.props.ChangeColor(oColor);
    this.refs.colorPicker.style.background = oColor; //this is how background will be updated

  },
Muhammad Ateeq Azam
  • 1,009
  • 1
  • 12
  • 26
  • 5
    Can someone elaborate on this answer? – Taylor A. Leach Aug 09 '19 at 21:37
  • 3
    Just one more thing: mutating one of the the style object's properties is very slow. You should wrap this is request in a [window.requestAnimationFrame()](https://developer.mozilla.org/en-US/docs/Web/API/window/requestAnimationFrame) call – Luis Paulo Oct 10 '20 at 20:20
  • Especially if the style you are changing is a transformation (i.e. `translate`, `top`, etc.) – Luis Paulo Oct 10 '20 at 20:21
9

If somebody is looking for the hooks version

export const YourComponent = (props) => {
  const divRef: = useRef(null);
  
  yourTriggerEvent = () => {
    divRef.current.style.background = 'red';
  }
  
  return (
    <div ref={divRef}>
    </div>
  );
}
Jonathan Guerrero
  • 341
  • 1
  • 4
  • 8
5

Also, you can change the color of the div with the ref element. For example:

const myReference = this.colorPicker.current // The DOM element
myReference.style.backgroundColor = "red"; // The style you want to apply
Osv
  • 771
  • 8
  • 7