Security News
PyPI Introduces Digital Attestations to Strengthen Python Package Security
PyPI now supports digital attestations, enhancing security and trust by allowing package maintainers to verify the authenticity of Python packages.
react-resize-detector
Advanced tools
The react-resize-detector is a React component designed to handle resize events for React elements. It provides a simple and efficient way to trigger a function or render logic when the size of an element changes. This is particularly useful in responsive designs and when elements need to adjust based on their container's dimensions.
Basic resize detection
This feature allows you to detect the size of a component and react to changes. The `useResizeDetector` hook provides `width`, `height`, and `ref` which you attach to the component you want to monitor. The component re-renders whenever the size changes, displaying the new dimensions.
import React from 'react';
import useResizeDetector from 'react-resize-detector';
const ResponsiveComponent = () => {
const { width, height, ref } = useResizeDetector();
return (
<div ref={ref}>
Size: {width} x {height}
</div>
);
};
export default ResponsiveComponent;
OnResize callback
This feature uses the `withResizeDetector` higher-order component to monitor size changes. It provides `width`, `height`, and an `onResize` callback that is triggered on every resize event. This is useful for performing actions or calculations based on the new size.
import React from 'react';
import { withResizeDetector } from 'react-resize-detector';
class MyComponent extends React.Component {
render() {
const { width, height, onResize } = this.props;
return (
<div onResize={onResize}>
Current size: {width} x {height}
</div>
);
}
}
export default withResizeDetector(MyComponent, {
handleWidth: true,
handleHeight: true,
onResize: (width, height) => console.log(`Resized to ${width} x ${height}`)
});
react-sizeme is another package that provides similar functionality to react-resize-detector. It allows components to respond to changes in size. However, react-sizeme uses a higher-order component approach primarily, which might be less convenient than hooks provided by react-resize-detector in functional components.
This package is a polyfill for the ResizeObserver API, which is used to report changes to the dimensions of an Element's content or border box. It's more of a low-level API compared to react-resize-detector, which provides React-specific abstractions and hooks for easier integration in React applications.
Nowadays browsers support element resize handling natively using ResizeObservers. The library uses these observers to help you handle element resizes in React.
š„ Tiny ~3kb
š¼ Written in TypeScript
š¦ Supports Function and Class Components
š Used by 90k repositories
š¦ Generating 70M+ downloads/year
No window.resize
listeners! No timeouts! No š viruses! :)
TypeScript-lovers notice: starting from v6.0.0 you may safely remove @types/react-resize-detector
from you deps list.
Container queries now work in all major browsers. It's very likely you can resolve your problem using pure CSS.
<div class="post">
<div class="card">
<h2>Card title</h2>
<p>Card content</p>
</div>
</div>
.post {
container-type: inline-size;
}
/* Default heading styles for the card title */
.card h2 {
font-size: 1em;
}
/* If the container is larger than 700px */
@container (min-width: 700px) {
.card h2 {
font-size: 2em;
}
}
npm i react-resize-detector
// OR
yarn add react-resize-detector
and
import { useResizeDetector } from 'react-resize-detector';
import { useResizeDetector } from 'react-resize-detector';
const CustomComponent = () => {
const { width, height, ref } = useResizeDetector();
return <div ref={ref}>{`${width}x${height}`}</div>;
};
import { useResizeDetector } from 'react-resize-detector';
const CustomComponent = () => {
const onResize = useCallback(() => {
// on resize logic
}, []);
const { width, height, ref } = useResizeDetector({
handleHeight: false,
refreshMode: 'debounce',
refreshRate: 1000,
onResize
});
return <div ref={ref}>{`${width}x${height}`}</div>;
};
import { useResizeDetector } from 'react-resize-detector';
const CustomComponent = () => {
const targetRef = useRef();
const { width, height } = useResizeDetector({ targetRef });
return <div ref={targetRef}>{`${width}x${height}`}</div>;
};
import { withResizeDetector } from 'react-resize-detector';
const CustomComponent = ({ width, height }) => <div>{`${width}x${height}`}</div>;
export default withResizeDetector(CustomComponent);
import ReactResizeDetector from 'react-resize-detector';
// ...
<ReactResizeDetector handleWidth handleHeight>
{({ width, height }) => <div>{`${width}x${height}`}</div>}
</ReactResizeDetector>;
import React, { Component } from 'react';
import { withResizeDetector } from 'react-resize-detector';
const containerStyles = {
height: '100vh',
display: 'flex',
alignItems: 'center',
justifyContent: 'center'
};
class AdaptiveComponent extends Component {
state = {
color: 'red'
};
componentDidUpdate(prevProps) {
const { width } = this.props;
if (width !== prevProps.width) {
this.setState({
color: width > 500 ? 'coral' : 'aqua'
});
}
}
render() {
const { width, height } = this.props;
const { color } = this.state;
return <div style={{ backgroundColor: color, ...containerStyles }}>{`${width}x${height}`}</div>;
}
}
const AdaptiveWithDetector = withResizeDetector(AdaptiveComponent);
const App = () => {
return (
<div>
<p>The rectangle changes color based on its width</p>
<AdaptiveWithDetector />
</div>
);
};
export default App;
import React, { useState, useEffect } from 'react';
import { withResizeDetector } from 'react-resize-detector';
const containerStyles = {
height: '100vh',
display: 'flex',
alignItems: 'center',
justifyContent: 'center'
};
const AdaptiveComponent = ({ width, height }) => {
const [color, setColor] = useState('red');
useEffect(() => {
setColor(width > 500 ? 'coral' : 'aqua');
}, [width]);
return <div style={{ backgroundColor: color, ...containerStyles }}>{`${width}x${height}`}</div>;
};
const AdaptiveWithDetector = withResizeDetector(AdaptiveComponent);
const App = () => {
return (
<div>
<p>The rectangle changes color based on its width</p>
<AdaptiveWithDetector />
</div>
);
};
export default App;
We still support other ways to work with this library, but in the future consider using the ones described above. Please let me know if the examples above don't fit your needs.
The below explanation doesn't apply to useResizeDetector
The library is trying to be smart and does not add any extra DOM elements to not break your layouts. That's why we use findDOMNode
method to find and attach listeners to the existing DOM elements. Unfortunately, this method has been deprecated and throws a warning in StrictMode.
For those who want to avoid this warning, we are introducing an additional property - targetRef
. You have to set this prop as a ref
of your target DOM element and the library will use this reference instead of searching the DOM element with help of findDOMNode
import { withResizeDetector } from 'react-resize-detector';
const CustomComponent = ({ width, height, targetRef }) => <div ref={targetRef}>{`${width}x${height}`}</div>;
export default withResizeDetector(CustomComponent);
import ReactResizeDetector from 'react-resize-detector';
// ...
<ReactResizeDetector handleWidth handleHeight>
{({ width, height, targetRef }) => <div ref={targetRef}>{`${width}x${height}`}</div>}
</ReactResizeDetector>;
Prop | Type | Description | Default |
---|---|---|---|
onResize | Func | Function that will be invoked with width and height arguments | undefined |
handleWidth | Bool | Trigger onResize on width change | true |
handleHeight | Bool | Trigger onResize on height change | true |
skipOnMount | Bool | Do not trigger onResize when a component mounts | false |
refreshMode | String | Possible values: throttle and debounce See lodash docs for more information. undefined - callback will be fired for every frame | undefined |
refreshRate | Number | Use this in conjunction with refreshMode . Important! It's a numeric prop so set it accordingly, e.g. refreshRate={500} | 1000 |
refreshOptions | Object | Use this in conjunction with refreshMode . An object in shape of { leading: bool, trailing: bool } . Please refer to lodash's docs for more info | undefined |
observerOptions | Object | These options will be used as a second parameter of resizeObserver.observe method. | undefined |
targetRef | Ref | Use this prop to pass a reference to the element you want to attach resize handlers to. It must be an instance of React.useRef or React.createRef functions | undefined |
Thanks to @Primajin for posting this snippet
const { ResizeObserver } = window;
beforeEach(() => {
delete window.ResizeObserver;
window.ResizeObserver = jest.fn().mockImplementation(() => ({
observe: jest.fn(),
unobserve: jest.fn(),
disconnect: jest.fn()
}));
wrapper = mount(<MyComponent />);
});
afterEach(() => {
window.ResizeObserver = ResizeObserver;
jest.restoreAllMocks();
});
it('should do my test', () => {
// [...]
});
MIT
Show us some love and STAR ā the project if you find it useful
FAQs
React resize detector
The npm package react-resize-detector receives a total of 248,152 weekly downloads. As such, react-resize-detector popularity was classified as popular.
We found that react-resize-detector demonstrated a healthy version release cadence and project activity because the last version was released less than a year ago.Ā It has 2 open source maintainers collaborating on the project.
Did you know?
Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.
Security News
PyPI now supports digital attestations, enhancing security and trust by allowing package maintainers to verify the authenticity of Python packages.
Security News
GitHub removed 27 malicious pull requests attempting to inject harmful code across multiple open source repositories, in another round of low-effort attacks.
Security News
RubyGems.org has added a new "maintainer" role that allows for publishing new versions of gems. This new permission type is aimed at improving security for gem owners and the service overall.