Master-Chief Master-Chief - 5 months ago 12
CSS Question

Get color of target html element in React

Trying to get the color of an html element using react, to pass to to my redux action/reducer.

JSX

<div>
<button styleName="css_toggle" id ="css" onClick {this.handleClick}>CSS</button>
</div>


Event Handler

handleClick(e){
const{dispatch} = this.props;
console.log(`e.target: ${e.target.style}`);
dispatch(CurrView(e.target.id, e.target.style.background));
}


Console/redux console returns empty values for all styles.

I am using react-css-modules/css-modules, and that is the only anomaly I can think of.

Any ideas are more than welcome, thank you.

Edit: I have create a branch for this project, specifically for this stackoverflow question: https://github.com/CharlieGreenman/pixelLight/tree/stackoverflow-37583025

Note: The data flow of this app, is that there is a single static value, which populates the rest of the app which is dynamic. In response, to suggestion(s), after much thought, I have decided this is the proper way to architect the app.

Answer

In the end, I used

const backgroundStyle = window.getComputedStyle(e.target, null).getPropertyValue("background-color");

and that allowed me to get the proper value. I would assume this is as result of two things going on, in this app.

  1. Style tags are being injected in the html directly. Not 100% if it as a result of webpack-dev-server or react-css-modules.
  2. Styles are only applied after react app is initialized, with proper settings applied.

So there it is, in this situation, getting the computed style is what did it for me. I am still in the process of looking into particular details. Thank you.

Comments