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()
You already get the style, the reason why CSSStyleDeclaration object's props have so much empty string value is it's link to the inner style.
See what will happen if you make change like below:
<div ref={"container"} className={"container"} style={{ width: 100 }}></div>
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);
}
It's worth noting that while ReactDOM.findDOMNode is usable today, it will be deprecated in the future in place of callback refs.
There is a post here by Dan Abramov which outlines reasons for not using findDOMNode while providing examples of how to replace the use of ReactDOM.findDOMNode with callback refs.
Since I've seen SO users get upset when only a link was included in an answer, so I will pass along one of the examples Dan has kindly provided:
**Before:**
class MyComponent extends Component {
componentDidMount() {
findDOMNode(this.refs.something).scrollIntoView();
}
render() {
return (
<div>
<div ref='something' />
</div>
)
}
}
**After:**
class MyComponent extends Component {
componentDidMount() {
this.something.scrollIntoView();
}
render() {
return (
<div>
<div ref={node => this.something = node} />
</div>
)
}
}
You should use ReactDOM.findDOMNode
method and work from there. Here's the code that does what you need.
var Hello = React.createClass({
componentDidMount: function() {
var elem = ReactDOM.findDOMNode(this.refs.container);
console.log(elem.offsetWidth, elem.offsetHeight);
},
render: function() {
return (
<div ref={"container"} className={"container"}>
Hello world
</div>
);
}
});
ReactDOM.render(
<Hello name="World" />,
document.getElementById('container')
);
jsFiddle
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>
}
}