Home > Blockchain >  How do I use a useRef hook in a text input field in React Native
How do I use a useRef hook in a text input field in React Native

Time:02-06

What would be the React Native equivalent of the following React code. The code is using a useRef hook to take the value of a user input in a form, and then use that input in an api call. The regular React code works in a brower just fine. The React Native code alert(name.current.value)} is undefined. I think I'm having a problem with the React Native text input and useRef hook syntax.

this is the react code:

import React, { useRef } from 'react'
import { doc, setDoc } from 'firebase/firestore'
import { db } from './firebase'

export default function AddNew({ path }) {
  const name = useRef()
  async function handleSubmit(e) {
    e.preventDefault()

    // API calls

    const docRef = doc(db, path, name.current.value)
    await setDoc(docRef, { name: name.current.value })
    console.log(name.current.value)

    e.target.reset()
  }

  return (
    <li>
      <form onSubmit={handleSubmit}>
        <input ref={name} />
        <button type='submit'>Add</button>
      </form>
    </li>
  )
}

and this is what I've been trying with React Native:

import React, { useRef } from 'react'
import {
  View,
  Text,
  TextInput,
  TouchableOpacity,
} from 'react-native'

import { doc, setDoc } from '@firebase/firestore'
import { db } from '../firebase'

export default function ({ path }) {
  const name = useRef(null)

  async function handleSubmit() {
    // API calls
    const docRef = doc(db, path, name.current.value)
    await setDoc(docRef, { name: name.current.value })

  }

  return (
    <View>
      <TextInput
        style={AppStyles.textInputAddCatStats}
        placeholder='Enter cat name'
        ref={name}
        onSubmitEditing={() => alert(name.current.value)}
      />
      <TouchableOpacity onPress={handleSubmit}>
        <Text>Submit</Text>
      </TouchableOpacity>
    </View>
  )
}

the alert(name.current.value)} is undefined is the react native code.

thanks for any help

CodePudding user response:

value is not available in native, possible to fake it like this, if for some reason state cannot be used.

<TextInput
...
  ref={name}
  onChangeText={(e) => name.current.value = e}
  onSubmitEditing={() => console.log(name.current.value)}
/>
  • Related