Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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;
like image 716
TeamBeamo Avatar asked Oct 24 '25 10:10

TeamBeamo


1 Answers

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;
like image 169
firats Avatar answered Oct 27 '25 06:10

firats



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!