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
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)}
/>