Languages
[Edit]
EN

React - custom AutoSizer component

8 points
Created by:
Kate_C
22870

In this article, we would like to show how in React monitor the current size of some div element with custom AutoSizer component.

AutoSizer let to handle onResize event inside children area.

// ONLINE-RUNNER:browser;

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

const AutoSizer = React.memo(({ interval, children, ...other }) => {
	const reference = React.useRef();
	const [size, setSize] = React.useState();
	React.useEffect(() => {
      	let storedWidth = size?.width;
      	let storedHeight = size?.height;
      	const id = setInterval(() => {
          	const element = reference.current;
        	if (element) {
              	const width = element.offsetWidth;
                const height = element.offsetHeight;
              	if (width != storedWidth || height != storedHeight) {
                  	storedWidth = width;
                  	storedHeight = height;
                    setSize({ width, height });
                }
            }
        }, interval ?? 100);
      	return () => {
        	clearInterval(id);
        }; 
	}, [interval]);
	return (
	  <div ref={reference} {...other}>
        {size && children && children(size.width, size.height)}
	  </div>
	);
});

// Usage example:

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

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

ReactJS

React - custom AutoSizer component
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