Languages
[Edit]
EN

React - get react component size before render operation

6 points
Created by:
AnnLen
11260

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 providesAutoSizer┬ácomponent.

1. Getting element size with functional 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.

// ONLINE-RUNNER:browser;

// Uncomment next line during working with JSX Compiler:
// import React from 'react';
// import ReactDOM from 'react-dom';

const Container = props => {
	const reference = React.useRef();
	const [dimensions, setDimensions] = React.useState({ width: 0, height: 0 });
	React.useEffect(() => {
		if (reference.current) {
			setDimensions({
				width: reference.current.offsetWidth,
				height: reference.current.offsetHeight
			});
		}
	}, []);
	return (
		<div ref={reference}>
			<pre>
				Container:<br />
				- width: {dimensions.width}<br />
				- height: {dimensions.height}
			</pre>
		</div>
	);
};

const App = () => (
	<div style={{background: '#e1e1e1', width: '400px'}}>
		<h1>My page!</h1>
		<Container />
	</div>
);

const root = document.querySelector('#root');
ReactDOM.render(<App />, root );

2. Getting element size with class component

In this axample ref attribute is used to get element reference. Container componen is created with class based approach.

// ONLINE-RUNNER:browser;

// Uncomment next line during working with JSX Compiler:
// import React from 'react';
// import ReactDOM from 'react-dom';

class Container extends React.Component {
	constructor(props) {
		super(props);
		this.state = {
			dimensions: null
		};
	}
	componentDidMount() {
		setTimeout(() => this.update());
	}
	update() {
		this.setState({
			dimensions: {
				width: this.container.offsetWidth,
				height: this.container.offsetHeight,
			}
		});
	}
	render() {
		const { dimensions } = this.state;
		return (
			<div ref={e => (this.container = e)}>
				<pre>
					Container:<br />
					- width: {dimensions && dimensions.width}<br />
					- height: {dimensions && dimensions.height}
				</pre>
			</div>
		);
	}
}

const App = () => (
	<div style={{background: '#e1e1e1', width: '400px'}}>
		<h1>My page!</h1>
		<Container />
	</div>
);

const root = document.querySelector('#root');
ReactDOM.render(<App />, root );

ReactJS

Native Advertising
­čÜÇ
Get your tech brand or product in front of software developers.
For more information Contact us
Dirask - we help you to
solve coding problems.
Ask question.

ÔŁĄ´ŞĆ­čĺ╗ ­čÖé

Join