Component-wrapper to determine and report children elements height

Last update: Jun 15, 2022

react-height npm

CircleCI Dependencies Dev Dependencies

Component-wrapper to determine and report children elements height

React Height

Goals

  • react-height keeps things simple, therefore it does not support nested height change, it only checks immediate children change
  • not based on specific browser APIs, so can be used in other environments too

React Height

Demo

https://nkbt.github.io/react-height

Codepen demo

https://codepen.io/nkbt/pen/NGzgGb

Installation

NPM

npm install --save react-height

yarn

yarn add react-height 

1998 Script Tag:

<script src="https://unpkg.com/react/umd/react.production.min.js"></script>
<script src="https://unpkg.com/react-height/build/react-height.js"></script>
(Module exposed as `ReactHeight`)

Usage

import {ReactHeight} from 'react-height';

<ReactHeight onHeightReady={height => console.log(height)}>
  <div>Random content</div>
</ReactHeight>

Options

onHeightReady: PropTypes.func.isRequired

Callback, invoked when height is measured (and when it is changed).

getElementHeight: PropTypes.func

Function to measure your element. It receives the element as argument and defaults to el => el.clientHeight.

children: PropTypes.node.isRequired

One or multiple children with static, variable or dynamic height.

<ReactHeight onHeightReady={height => console.log(height)}>
  <p>Paragraph of text</p>
  <p>Another paragraph is also OK</p>
  <p>Images and any other content are ok too</p>
  <img src="nyancat.gif" />
</ReactHeight>

hidden: PropTypes.bool (default: false)

ReactHeight can render to null as soon as height is measured.

<ReactHeight hidden={true} onHeightReady={height => console.log(height)}>
  <div>Will be removed from the DOM when height is measured</div>
</ReactHeight>

Pass-through props

All other props are applied to a container that is being measured. So it is possible to pass style or className, for example.

<ReactHeight onHeightReady={height => console.log(height)}
  style={{width: 200, border: '1px solid red'}}
  className="myComponent">

  <div>
    Wrapper around this element will have red border, 200px width
    and `class="myComponent"`
  </div>
</ReactHeight>

Development and testing

Currently is being developed and tested with the latest stable Node on OSX.

To run example covering all ReactHeight features, use yarn start, which will compile example/index.js

git clone [email protected]:nkbt/react-height.git
cd react-height
yarn install
yarn start

# then
open http://localhost:8080

Tests

# to run ESLint check
yarn lint

# to run tests
yarn test

License

MIT

GitHub

https://github.com/nkbt/react-height
Comments
  • 1. Height not updating when content inside container changes?

    I've noticed that the height doesn't seem to be updating when the content inside the container changes. The height just stays the same after the initial render. Is there anyway i can get it to re-measure the height?

    I have some dumb components that receive json and render out to the view. I want to be able to track the height of the containers of each of the items, but when changing the route and the json response, the height does not update on the containers, it just stays as the original value :/ I have to physically refresh the page for the heights to update to the new values.

    What is the dirty param used for? (it doesn't seem to fix my issue)

    Reviewed by KingScooty at 2016-06-12 20:29
  • 2. Allow [email protected] in peerDep

    react-addons-pure-render-mixin has been moved to peer dependency because react-addons-pure-render-mixin v0.14 will have peer dependency on react 0.14. Any project that is using react v15 will see peer dependency error if react-addons-shallow-compare is present under dependencies.

    Reviewed by vramana at 2016-04-09 22:29
  • 3. Usage instructions

    Hi, I'm hoping you might be able to help me troubleshoot basic usage of this package (in react-native).

    This is an example working component:

    import React, { Component } from 'react';
    import {View, Text} from 'react-native';
    
    export default class MyComponent extends Component {
      render(){
        return (
          <View>
            <Text>Hello world</Text>
          </View>
        )
      }
    }
    
    

    This is my first attempt to use ReactHeight, which throws Expected a component class, got [object Object].:

    import React, { Component } from 'react';
    import {View, Text} from 'react-native';
    import ReactHeight from 'react-height';
    
    export default class MyComponent extends Component {
      render(){
        return (
          <ReactHeight onHeightReady={height => console.log(height)}>
            <View>
              <Text>Hello world</Text>
            </View>
          </ReactHeight>
        )
      }
    }
    

    What am I doing wrong?

    Reviewed by s2t2 at 2016-10-21 00:36
  • 4. Height reported is not correct

    I'm seeing a strange issue where the height reported is too small. I'm just trying to calculate the height of a simple Bootstrap Alert component:

            <ReactHeight onHeightReady={(h)=> console.log('height is '+h)}>
                <div className="alert alert-success">
                  <strong>Testing!</strong>This is what an alert would look like.
                </div>
            </ReactHeight>
    

    I'm getting back a height of 18, though the actual height is closer to 50 with margins and padding. I tried to implement the logic of React Height myself, and was seeing similar behavior when querying the offsetHeight of the DOM node in a lifecycle function like componentDidMount. However if I checked the DOM node height inside of a setTimeout (even with a timeout of 0), I got the correct height.

    It seems like Chrome won't give the height until after the parent or maybe even the full page is rendered for some reason.

    Have you ever run into this?

    Reviewed by jlevycpa at 2016-06-21 21:50
  • 5. TypeScript Types

    We only write TS projects nowadays but when using this library I get the error: Could not find a declaration file for module 'react-height'. 'index.js' implicitly has an 'any' type. Trynpm i --save-dev @types/react-heightif it exists or add a new declaration (.d.ts) file containingdeclare module 'react-height';

    Is it possible to create a type file?

    Reviewed by rogerfar at 2021-05-28 15:08
  • 6. Invalid initial height in demos / first render

    This page http://nkbt.github.io/react-height/example/ shows an initial height of 18px. screen shot 2017-01-25 at 8 36 46 pm

    But in reality, the content height for a paragraph is 70px, while the block is 152px.

    The onHeightReady doesn't seem to be called on the first render, and I'm having the same issue in my app as well...

    Reviewed by tleunen at 2017-01-26 01:39
  • 7. Update prop-types to 15.5.10

    Hello.

    Using your library we have a warning "Calling PropTypes validators directly is not supported by the prop-types"

    This question has already been discussed here: https://github.com/malte-wessel/react-custom-scrollbars/issues/153 and people advice to update prop-types to 15.5.10

    Thank you.

    Reviewed by leonidsheremeto at 2018-03-15 11:35
  • 8. Error with Hidden prop

    Hi,

    When I use the hidden prop, I have an error in the console :

    bundle.min.js:206314 Uncaught TypeError: Cannot read property 'clientHeight' of null
        at Object.getElementHeight (bundle.min.js:206314)
        at ReactHeight.componentDidUpdate (bundle.min.js:206363)
        at measureLifeCyclePerf (bundle.min.js:56076)
        at bundle.min.js:56730
        at CallbackQueue.notifyAll (bundle.min.js:48644)
        at ReactReconcileTransaction.close (bundle.min.js:59436)
        at ReactReconcileTransaction.closeAll (bundle.min.js:49827)
        at ReactReconcileTransaction.perform (bundle.min.js:49774)
        at ReactUpdatesFlushTransaction.perform (bundle.min.js:49761)
        at ReactUpdatesFlushTransaction.perform (bundle.min.js:48401)
    

    The content is null with this prop, but why I have the error ?

    Thanks.

    Reviewed by Themandunord at 2017-06-28 13:56
  • 9. Migrated deprecated React.PropTypes and React.createClass

    I think we should migrate to the es6 class syntax and stop using React.createClass, but that would be another step. For now just created this PR, so people stop having deprecation warnings after migration to React v15.5.

    If you feel the same about class, I'll create an issue about it, so the matter won't get forgotten and neglected.

    Reviewed by Andarist at 2017-04-08 11:27
  • 10. Replace import of shouldComponentUpdate with shallowCompare

    The current code imports shouldComponentUpdate directly from the bowels of React; this trips over Preact compatibility. This change loads shallowCompare in the documented way, which allows Preact magic to be applied.

    Reviewed by darobin at 2016-09-27 20:12
  • 11. Could you create a new release ?

    Reviewed by baptwaels at 2019-04-11 12:34
  • 12. Fix componentWIllReceiveProps warning

    Currently this package triggers React's warnings:

    image

    At the very least we can rename this method to UNSAFE_componentWIllReceiveProps or better yet fix it properly.

    Reviewed by dimaip at 2019-12-27 07:30
  • 13. infinite loop with setState( { dirty...}

    Maximum update depth exceeded. This can happen when a component repeatedly calls setState inside componentWillUpdate or componentDidUpdate. React limits the number of nested updates to prevent infinite loops.

    {snip} .getElementHeight(this.wrapper);t===this.state.height?this.setState({dirty:!1}):this.setState({height:t,dirty:!1},function(){return e.props. {snip}
    

    Code:

            <ReactHeight onHeightReady={ height => setHiddenContent( height > props.maxHeight )}>
              {
                hidden_content &&
                  <div
                    style={{
                        top: '120px',
                        height: '80px',
                        width: '100%',
                        position: 'absolute',
                        backgroundImage: 'url(/assets/images/mensajero/degradado.png)',
                    }}
                  />
              }
              { props.children.contentToCollapse }
            </ReactHeight>
    
    Reviewed by tcoldmf at 2019-09-05 16:34
Make your React Components aware of their width and height!
Make your React Components aware of their width and height!

Make your React Components aware of their width and/or height! Blazingly fast. ?? Responsive Components! Easy to use. Extensive browser support. Suppo

Jun 21, 2022
Wrapper component that detects element resize and passes new dimensions down the tree. Based on https://github.com/wnr/element-resize-detector

react-container-dimensions Wrapper component that detects parent (container) element resize and passes new dimensions down the tree. Based on element-

Jun 14, 2022
Sensor component for React that notifies you when it goes in or out of the window viewport.

React Visibility Sensor Sensor component for React that notifies you when it goes in or out of the window viewport. Sponsored by X-Team Install npm in

Jun 17, 2022
A React component to execute a function whenever you scroll to an element.
A React component to execute a function whenever you scroll to an element.

React Waypoint A React component to execute a function whenever you scroll to an element. Works in all containers that can scroll, including the windo

Jun 27, 2022
📏 Compute measurements of a React component.

?? React Measure Compute measurements of React components. Uses a ResizeObserver to detect when an element's dimensions have changed. Includes a polyf

Jun 13, 2022
Component-wrapper for collapse animation with react-motion for elements with variable (and dynamic) height
Component-wrapper for collapse animation with react-motion for elements with variable (and dynamic) height

react-collapse Component-wrapper for collapse animation for elements with variable (and dynamic) height Demo http://nkbt.github.io/react-collapse Code

Jun 24, 2022
Component-wrapper for collapse animation with react-motion for elements with variable (and dynamic) height
Component-wrapper for collapse animation with react-motion for elements with variable (and dynamic) height

Component-wrapper for collapse animation with react-motion for elements with variable (and dynamic) height

May 30, 2022
Extended utils for ⚛️ React.Children data structure that adds recursive filter, map and more methods to iterate nested children.
Extended utils for ⚛️  React.Children data structure that adds recursive filter, map and more methods to iterate nested children.

React Children Utilities Recursive and extended utils for React children opaque data structure. Installation Available as a package and can be added t

Jun 17, 2022
F.A.N Report - Facebook Audience Network Performance Tool (available both iOS and Android).
F.A.N Report - Facebook Audience Network Performance Tool (available both iOS and Android).

Audience Network - Facebook Ads Performance Tool Check your Facebook Audience Network performance quickly with the app. It shows number of ad requests

Feb 14, 2022
Weather-App - A Web application shows dynamic weather report using Reactjs and openweather
Weather-App - A Web application shows dynamic weather report using Reactjs and openweather

Screenshots of this project Getting Started with Create React App This project w

Jan 28, 2022
React component that renders children elements when they enter the viewport.

React Lazy Load Component React Lazy Load is easy to use React component which helps you defer loading content in predictable way. It's fast, works in

Jun 19, 2022
☯️ React hook to determine if you are on the server, browser, or react native
☯️ React hook to determine if you are on the server, browser, or react native

useSSR ☯️ React hook to determine if you are on the server, browser, or react native Need to know when you're on the server, in the browser or in reac

Apr 15, 2022
Determine the cursor aim for triggering mouse events.
Determine the cursor aim for triggering mouse events.

React Aim Determine the cursor aim for triggering mouse events. Demo Try the demo here. Installation npm install react-aim --save Usage import React,

May 22, 2022
Native modules to determine if a location is within defined geographical boundaries using Google Geometry library
Native modules to determine if a location is within defined geographical boundaries using Google Geometry library

react-native-geo-fencing Native modules to determine if a location is within defined geographical boundaries using Google Geometry library for ios and

May 15, 2022
React Navigation for React js that tries to ensure that the elements of the navigators display correctly on devices with notches and UI elements which may overlap the app content.
React Navigation for React js that tries to ensure that the elements of the navigators display correctly on devices with notches and UI elements which may overlap the app content.

React Navigation for React js that tries to ensure that the elements of the navigators display correctly on devices with notches (e.g. iPhone X) and UI elements which may overlap the app content.

Dec 7, 2021
@custom-elements-manifest/analyzer plugin to ✨ automatically ✨ create react wrappers for your custom elements

cem-plugin-reactify @custom-elements-manifest/analyzer plugin to automatically create React wrappers for your custom elements based on your custom ele

Oct 6, 2021
A wrapper for placing elements along div borders.
A wrapper for placing elements along div borders.

Test in Browser Installation npm npm install react-border-wrapper yarn yarn add react-border-wrapper Usage Use the border wrapper in the same way you

May 2, 2022
A ReactJS component that can sort any children with touch support and IE8 compatibility
A ReactJS component that can sort any children with touch support and IE8 compatibility

This project is in INACTIVE status, bugfix will be maintained, but no new feature will be added. Feel free to use it if it suits your need, for compli

May 27, 2022
:performing_arts: A simple and lightweight RN component that fades in its children

react-native-fade-in-view A simple and lightweight RN component that fades in its children Install yarn add react-native-fade-in-view or npm install r

Nov 27, 2021
A React component that can virtualise lists and any set of children.

A list virtualiser that can create virtual rows out of arrays or a total count, or virtualise an arbitrary set of React components.

May 3, 2022