EN
React - get react component size before render operation
6 points
In this article, we're going to have a look at how to get component size before rendering in React.
Notes:
- read this article to see simple custom
AutoSizer
implementation,- read this article to see external library that provides
AutoSizer
component.
In this axample useRef
function with ref
attribute are used to get current size of element. Container component is created with function based approach.
xxxxxxxxxx
1
// Uncomment next line during working with JSX Compiler:
2
// import React from 'react';
3
// import ReactDOM from 'react-dom';
4
5
const Container = props => {
6
const reference = React.useRef();
7
const [dimensions, setDimensions] = React.useState({ width: 0, height: 0 });
8
React.useEffect(() => {
9
if (reference.current) {
10
setDimensions({
11
width: reference.current.offsetWidth,
12
height: reference.current.offsetHeight
13
});
14
}
15
}, []);
16
return (
17
<div ref={reference}>
18
<pre>
19
Container:<br />
20
- width: {dimensions.width}<br />
21
- height: {dimensions.height}
22
</pre>
23
</div>
24
);
25
};
26
27
const App = () => (
28
<div style={{background: '#e1e1e1', width: '400px'}}>
29
<h1>My page!</h1>
30
<Container />
31
</div>
32
);
33
34
const root = document.querySelector('#root');
35
ReactDOM.render(<App />, root );
In this axample ref
attribute is used to get element reference. Container componen is created with class based approach.
xxxxxxxxxx
1
// Uncomment next line during working with JSX Compiler:
2
// import React from 'react';
3
// import ReactDOM from 'react-dom';
4
5
class Container extends React.Component {
6
constructor(props) {
7
super(props);
8
this.state = {
9
dimensions: null
10
};
11
}
12
componentDidMount() {
13
setTimeout(() => this.update());
14
}
15
update() {
16
this.setState({
17
dimensions: {
18
width: this.container.offsetWidth,
19
height: this.container.offsetHeight,
20
}
21
});
22
}
23
render() {
24
const { dimensions } = this.state;
25
return (
26
<div ref={e => (this.container = e)}>
27
<pre>
28
Container:<br />
29
- width: {dimensions && dimensions.width}<br />
30
- height: {dimensions && dimensions.height}
31
</pre>
32
</div>
33
);
34
}
35
}
36
37
const App = () => (
38
<div style={{background: '#e1e1e1', width: '400px'}}>
39
<h1>My page!</h1>
40
<Container />
41
</div>
42
);
43
44
const root = document.querySelector('#root');
45
ReactDOM.render(<App />, root );