Languages
[Edit]
DE

React - AutoSizer-Komponente

3 points
Created by:
Nikki
10520

In diesem Artikel wird gezeigt, wie man in React die aktuelle Größe eines div-Elements mit hilfe der AutoSizer-Komponente kontrollieren kann. 

Mit AutoSizer kann man das Ereignis onResize bearbeiten. 

// ONLINE-RUNNER:browser;

// Hinweis: Bei der Arbeit mit dem JSX-Compiler soll man die Importzeilen entkommentieren:
// 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>
	);
});

// Beispiel:

const App = () => (
  <div>
    <h1>Meine Webseite!</h1>
    <AutoSizer style={{background: '#e1e1e1', width: '400px'}}>
      {(width, height) => {
      	return (
          <pre>
			Container:<br />
			- Breite: {width}<br />
			- Höhe: {height}
		  </pre>
        );
      }}
    </AutoSizer>
  </div>
);

const root = document.querySelector('#root');
ReactDOM.render(<App />, root );
Donate to Dirask
Our content is created by volunteers - like Wikipedia. If you think, the things we do are good, donate us. Thanks!
Join to our subscribers to be up to date with content, news and offers.

ReactJS (DE)

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