3

I have a ref to a ScrollView and need to get its height. It doesn't seem to have a height property:

import React, { useRef, useEffect } from "react";
import { View, ScrollView } from "react-native";
function Component() {
  const scrollView = useRef(null);
  useEffect(
    function() {
      // All of these print undefined
      console.log(scrollView.height);
      console.log(scrollView.current.height);
      console.log(scrollView.current.clientHeight);
    },
    [scrollView]
  );

  return (
    <ScrollView ref={scrollView}>
      <View style={{ height: 800, width: 100 }} />
    </ScrollView>
  );
}

How do I simply get the height of the scrollView from the ref? It is possible in ReactJS but I'm not sure about react-native.

I would like to do this without using onLayout if that is possible. If onLayout is the only way then please let me know.

ICW
  • 4,875
  • 5
  • 27
  • 33
  • Does this answer your question? [Get size of a View in React Native](https://stackoverflow.com/questions/30203154/get-size-of-a-view-in-react-native) – StackedQ Mar 19 '20 at 14:41
  • @Qiarash Not exactly. I'm aware onLayout can be used to get the height of an element after the view is laid out, but I'd like the ability to get the height from the ref itself without using the onLayout callback. It might be that the only way to get the height is the onLayout callback though. I just feel like a ref should have that information as well. – ICW Mar 19 '20 at 14:45
  • I'm fairly confident `onLayout` is the only way to do this. But if you want to abstract that out of your business logic then you can build a wrapper around ScrollView that saves the layout height and width to state. Then you could access it from the ref. – Benjamin Godlove Mar 21 '20 at 20:55

1 Answers1

1

Try changing this

useEffect(
function() {
  ...
},
[scrollView]
);

to:

useEffect(
function() {
  if (!scrollView.current) {
        console.log("scrollView not mounted to DOM yet");
  } else {
          // Get scrollViewHeight here
         }
},[scrollView.current]
);

Let me know if it works!

  • 1
    The problem is not the useEffect function running, it runs properly whenever scrollView ref is set. The problem is that I cannot find a property within `scrollView.current` that gives me the height of the element. I'm able to access the scrollView just fine, just having trouble getting the height from the ref. – ICW Mar 20 '20 at 16:00
  • Please note that in order for the scrollView element to have a "height", its CSS style need to be fully loaded. The scrollView.current point to the scrollView element that is mounted on the screen and after all the CSS styles already applied if it has any. Therefore what you need to do inside useEffect() is to check if scrollView.current (not scrollView) exists, then if it's true print out scrollView.current.scrollHeight. – Nguyễn Hải Mar 24 '20 at 09:44