0

I want to get the x, y position when the text cursor is focused on TextInput.

how to get ref position?

here is my code

const Code = () => {
  const emailInput = useRef();
  const scrollViewRef = useRef();

  const [email, setEmail] = useState<string>('');


  const scrollToEmail = () => {
// I want to scroll the y position of the scroll to the center where the TextInput's cursor is focused.
  };

  return (
    <SafeAreaView style={{ flex: 1}}>
      <ScrollView keyboardShouldPersistTaps="handled" ref ={scrollViewRef}>
        <KeyboardAvoidingView enabled behavior={'padding'}>
     
          <TextInput
            ref={emailInput}
            value={email}
            returnKeyType="done"
            onChangeText={(text) => setEmail(text)}
            onFocus = {() => scrollToEmail()} <== function works here!
          />

        </KeyboardAvoidingView>
      </ScrollView>

    </SafeAreaView>
  );
};

export default Code;

i tried this

1.

const handler = findNodeHandle(emailInput.current); 
  console.log(
    emailInput.measure(handler, (x, y, width, height) => {
      console.log(y);
    }),
    ); <== TypeError: emailInput.measure is not a function 
const handler = findNodeHandle(emailInput.current); 
  console.log(emailInput.current.getBoundingClientRect()); <== TypeError: emailInput.current.getBoundingClientRect is not a function 

there is no way get the ref's postition in a functional component?

ppiu46414
  • 11
  • 3

1 Answers1

0

You can use onLayout prop on the ScrollView to the the height, width, X and Y value.

If you want to use the ref, you have to set or console.log the X and Y value on a useLayoutEffect. This is because you need to wait for the component to be rendered and "drawn" before you get the information, otherwise you will get only 0

  • i tryied onLayout but, onLayout catches the x,y of the parent component. If you have two TextInputs, onLayout is not very helpful. – ppiu46414 Mar 03 '21 at 01:58