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!
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.
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); }
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> } }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With