I have a react component that needs to know its dimensions ahead of time, before it renders itself.
When I\'d make a widget in jquery I could just <
As it was already mentioned, you can't get any element's dimensions until it is rendered to DOM. What you can do in React is to render only a container element, then get it's size in componentDidMount, and then render rest of the content.
I made a working example.
Please note that using setState in componentDidMount is an anti-pattern but in this case is fine, as it is exactly what are we trying to achieve.
Cheers!
Code:
import React, { Component } from 'react';
export default class Example extends Component {
state = {
dimensions: null,
};
componentDidMount() {
this.setState({
dimensions: {
width: this.container.offsetWidth,
height: this.container.offsetHeight,
},
});
}
renderContent() {
const { dimensions } = this.state;
return (
width: {dimensions.width}
height: {dimensions.height}
);
}
render() {
const { dimensions } = this.state;
return (
(this.container = el)}>
{dimensions && this.renderContent()}
);
}
}