Observe element size in react, using ResizeObserver polyfill. Edit
npm install react-observe-sizeThe Resize Observer spec will solve this problem. react-observe-size uses
resize-observer-polyfill and provides an easy to use interface
for React components.
npm install react-observe-size
or
yarn add react-observe-size
``jsx
import React from 'react';
import ObserveSize from 'react-observe-size';
const MyComponent = () =>
{({ width }) =>
...
}
const styles = {
small: {
// ...
},
large: {
// ...
}
}
`
OR if you need the dimensions outside of your render method:
`jsx
import React from 'react';
import ObserveSize from 'react-observe-size';
class MyComponent extends Component {
updateDimensions = (width, height) => {
// ...
};
render() {
const { renderWidth } = this.state
return (
...
)
}
}
`
You can also combine the two examples above if you need both use cases.
Note: on the first render there is no layout yet so the contentRect will have its values set to 0. You can define defaults
using the defaults prop to set values for the first render or you can choose to not render the first frame by checking
the values for 0:
Use defaults for first frame:
`jsx`
{({ width }) =>
...
}
Don't render first frame:
`jsx`
{({ width }) => width > 0 &&
...
}
element that gets a resize observer. Will unbind observer on unmount.| Property | Type | Required | Description |
|:---------|:-----|:---------|:------------|
| observerFn | ObserverFn | no | Callback function that gets called on first render and on every layout change |
| children |
Node or function (contentRect: ContentRect) => Node | no | The children of the div element that gets monitored |
| defaults | Partial<ContentRect> | no | Define defaults for first render. Can be useful for server-side rendering or to prevent flashes of first frame |$3
function (contentRect: ContentRect)`Callback function for the observer.
| Property | Type |
|:---------|:-----|
| width | number |
| height | number |
| bottom | number |
| top | number |
| left | number |
| right | number |