Reputation: 561
I am new with react native and when i try do this
<TextInput
style={styles.input}
onChange={(text) => setPontoValue(text)}
/>
i receive this error
TS2345: Argument of type 'NativeSyntheticEvent<TextInputChangeEventData>' is not assignable to parameter of type 'SetStateAction<undefined>'. Type 'NativeSyntheticEvent<TextInputChangeEventData>' provides no match for the signature '(prevState: undefined): undefined'.
all code is below
import React, { useState } from 'react'
import {
TextInput,
TouchableOpacity,
StyleSheet,
SafeAreaView,
Text,
View, Button,
} from 'react-native'
export default function App() {
const [pontoValue, setPontoValue] = useState()
const [dataValue, setDataValue] = useState()
return (
<SafeAreaView style={styles.container}>
<View style={styles.repositoryContainer}>
<TextInput
style={styles.input}
onChange={(text) => setPontoValue(text)}
/>
<TextInput
style={styles.input}
value={dataValue}
/>
<TouchableOpacity>
<Button
title="Calcular"
onPress={teste}>Converter
</Button>
</TouchableOpacity>
</View>
</SafeAreaView>
)
function teste() {
if (pontoValue) {
setDataValue(pontoValue.replace(/[ .]+/g, ''))
}
}
}
const styles = StyleSheet.create({
container: {
flex: 1,
justifyContent: 'center',
alignContent: 'center',
backgroundColor: '#7199c1',
},
repositoryContainer: {
marginBottom: 15,
marginHorizontal: 15,
backgroundColor: '#fff',
padding: 20,
},
input: {
height: 40,
padding: 5,
borderColor: 'gray',
borderWidth: 1,
},
buttonText: {
marginVertical: 11,
fontSize: 14,
fontWeight: 'bold',
color: '#fff',
backgroundColor: '#7159c1',
padding: 15,
},
})
Upvotes: 4
Views: 2513
Reputation: 199
onChange
returns a nativeEvent object that has the text
(string type) property that you need to set your state.
To resolve the problem, you have two options:
onChange
prop and access the text property from nativeEvent<TextInput
style={styles.input}
onChange={(event) => setPontoValue(event.nativeEvent.text)}
/>
onChangeText
prop<TextInput
style={styles.input}
onChangeText={(text) => setPontoValue(text)}
/>
Either way should work
Upvotes: 1
Reputation: 478
onChange
event returns an event object which has nativeEvent
function which providers access to the following properties: { eventCount, target, text}
you need the text
property, so you can use:
onChange={(event) => setPontoValue(event.nativeEvent.text)}
or
onChangeText={(text) => setPontoValue(text)}
Upvotes: 7
Reputation: 526
I suggest you to use onChangeText
prop.
onChangeText
is a prop that gives you only text changes.
onChange
on the other hand, passes an event.
So, try this
<TextInput
style={styles.input}
onChangeText={(text) => setPontoValue(text)}
/>
Also, always initialize your state variables.
const [pontoValue, setPontoValue] = useState('')
const [dataValue, setDataValue] = useState('')
It will reduce to chance of getting undefined
errors.
Hope it works.
Upvotes: 3