ICW
ICW

Reputation: 5760

Get React-Native Element's Height From Ref

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.

Upvotes: 3

Views: 4629

Answers (1)

Nguyễn Hải
Nguyễn Hải

Reputation: 23

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!

Upvotes: 1

Related Questions