Sign Up for Free

RunKit +

Try any Node.js package right in your browser

This is a playground to test code. It runs a full Node.js environment and already has all of npm’s 400,000 packages pre-installed, including react-dims with all npm packages installed. Try it out:

require("react/package.json"); // react is a peer dependency. var reactDims = require("react-dims")

This service is provided by RunKit and is not affiliated with npm, Inc or the package authors.

react-dims v1.0.8

Get the dimensions of any React DOM node - from the very first render.

React Dims

A React wrapper to use when you need a Child component to be aware of its own dimensions.

Maintenance Status

React-dims is a dimensions provider for React components, enabling you to make any React component self-aware of it's own width, height, x and y coordinates, by passing them down as props.

When the component is resized, props are updated, so the component is always aware of what it's own dimensions are.

Useful for things like getting the current dimensions of components that are housed within a CSS grid, or wrapping a responsive D3 chart so you can resize it dynamically using the new width and height.

Requires React version 16.8.0 or greater.

Installation

npm i react-dims

Usage

Use the react-dims Provider to wrap a child component, just like using any other Higher Order Component;

App.js

import { Provider } from 'react-dims';
import ChildNode from './ChildNode';

const App=()=>{
  return (
    <div className='myLayout'>
      <Provider>
        <ChildNode className='coolThing'/>
      </Provider>
    <div>
  )
}

export default App;

Export the child component by passing it to the react-dims withContext( ) method, similar to using Redux connect( );

ChildNode.js

import { withContext } from 'react-dims';

const ChildNode=({dims})=>{  
  return (
    <div>My height is: {dims.height}!</div>
  )
}

export default withContext(ChildNode);

Leverages the native .getBoundingClientRect( ) method, so props.dims will be an object that looks something like this;

{
  bottom: 113,
  height: 160,
  left: 213.015625,
  right: 286.96875,
  top: 97,
  width: 73.953125,
  x: 213.015625,
  y: 97
}

Adjusting Debounce Timer

When your component is resized, the Provider is throttled to fire at a default rate of once every 100ms. You can change the rate by simply passing the provider a prop of 'debounce' with a value which is a number, like so;

<Provider debounce={300}>
  <ChildNode/>
</Provider>

Usage with Redux

If your child component happens to be directly connected to Redux, for example to fetch data, just feed the component to the withContext( ) method, then wrap that entire statement with connect ( ) like so;


export default connect(mapStateToProps, { fetchData })(withContext(ChildNode));

RunKit is a free, in-browser JavaScript dev environment for prototyping Node.js code, with every npm package installed. Sign up to share your code.
Sign Up for Free