Search code examples
react-nativepositionreact-hooks

How do I find the component position in a functional react-native component


I am trying to dynamically find the position of my component after it has rendered. Im trying to use useRef and getBoundingClientRect() (see code below).

The response I get is this.

myRef.current.getBoundingClientRect is not a function. (In 'myRef.current.getBoundingClientRect()', 'myRef.current.getBoundingClientRect' is undefined).

Any ideas what I am doing wrong?

import React, { useState, useRef } from "react";
import { View, Button, TextInput } from "react-native";

const MyComponent = () => {
  const [value, onChangeText] = useState("Useless Placeholder");

  const myRef = useRef();

  const showRefPosition = () => {
    console.log("button clicked, set focus and log position");
    // this works and shows that i am using the ref correctly
    myRef.current.focus();

    // however, this does not work and throws the eror
    let componentPosition = myRef.current.getBoundingClientRect();
    console.log(`Component Position ${componentPosition}`);
  };

  return (
    <View>
      <TextInput
        style={{ height: 40, borderColor: "gray", borderWidth: 1 }}
        onChangeText={text => onChangeText(text)}
        value={value}
        ref={myRef}
      />
      <Button title="Click Me" onPress={() => showRefPosition()} />
    </View>
  );
};

export default MyComponent;

Solution

  • You can try measure method in react-native.

    import React, { useState, useRef } from "react";
    import { View, Button, TextInput } from "react-native";
    
    const MyComponent = () => {
      const [value, onChangeText] = useState("Useless Placeholder");
    
      const myRef = useRef();
    
      const showRefPosition = () => {
        console.log("button clicked, set focus and log position");
        // this works and shows that i am using the ref correctly
        this.ref.measure( (width, height) => {
          console.log('Component width is: ' + width)
          console.log('Component height is: ' + height)
        })
      };
    
      return (
        <View>
          <TextInput
            style={{ height: 40, borderColor: "gray", borderWidth: 1 }}
            onChangeText={text => onChangeText(text)}
            value={value}
            ref={(ref) => { this.ref = ref; }}
          />
          <Button title="Click Me" onPress={() => showRefPosition()} />
        </View>
      );
    };
    
    export default MyComponent;