Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to Access styles from React?

I am trying to access the width and height styles of a div in React but I have been running into one problem. This is what I got so far:

componentDidMount()  {   console.log(this.refs.container.style);      }   render()  {    return (       <div ref={"container"} className={"container"}></div>  //set reff    ); } 

This works but the output that I get is a CSSStyleDeclaration object and in the all property I can all the CSS selectors for that object but they none of them are set. They are all set to an empty string.

This is the output of the CSSStyleDecleration is: http://pastebin.com/wXRPxz5p

Any help on getting to see the actual styles (event inherrited ones) would be greatly appreciated!

Thanks!

like image 263
mre12345 Avatar asked Feb 03 '16 07:02

mre12345


People also ask

Can we use style in React?

Sharing styles across many React components The style objects and the components do not have to be in the same file. We can create a separate . js file for our styles, export these styles, and then import them into the component where we want to use them. Doing this makes styles reusable across multiple components.


2 Answers

For React v <= 15

console.log( ReactDOM.findDOMNode(this.refs.container).style); //React v > 0.14  console.log( React.findDOMNode(this.refs.container).style);//React v <= 0.13.3 

EDIT:

For getting the specific style value

console.log(window.getComputedStyle(ReactDOM.findDOMNode(this.refs.container)).getPropertyValue("border-radius"));// border-radius can be replaced with any other style attributes; 

For React v>= 16

assign ref using callback style or by using createRef().

assignRef = element => {   this.container = element; } getStyle = () => {    const styles = this.container.style;   console.log(styles);   // for getting computed styles   const computed = window.getComputedStyle(this.container).getPropertyValue("border-radius"));// border-radius can be replaced with any other style attributes;   console.log(computed); } 
like image 141
Vikramaditya Avatar answered Oct 01 '22 03:10

Vikramaditya


Here is an example of computing the CSS property value via React Refs and .getComputedStyle method:

class App extends React.Component {     constructor(props) {         super(props)         this.divRef = React.createRef()     }      componentDidMount() {         const styles = getComputedStyle(this.divRef.current)          console.log(styles.color) // rgb(0, 0, 0)         console.log(styles.width) // 976px     }      render() {         return <div ref={this.divRef}>Some Text</div>     } } 
like image 23
Purkhalo Alex Avatar answered Oct 01 '22 01:10

Purkhalo Alex