I'm trying to make a general onChange handler for multiple TextInput s. However when I access the event, the best I can get is event.nativeEvent which has 3 keys.
eventCount, target, and text
target is only a number. I realize from the docs that 'name' is not a prop of TextInput. Is there a way to pass in a prop to the TextInput so I can get it later in onChange and then set the state based on that?
I have 2 TextInputs like this
<TextInput
name='foo'
keyboardType='numeric'
maxLength={4}
onChange={this.handleChange}
/>
<TextInput
name='bar'
maxLength={4}
onChange={this.handleChange}
/>
Thanks
EDIT: Here is what I tried for putting id on TextInput
<TextInput
id='bar'
name='bar'
maxLength={4}
onChange={this.handleChange}
/>
handleChange(e) {
console.log(e.target.id);
const {name, type, text} = e.nativeEvent;
this.setState({baths: text});
}
An onChange event handler returns a Synthetic Event object which contains useful meta data such as the target input's id, name, and current value. We can access the target input's value inside of the handleChange by accessing e. target.
The difference is that onChange sends an event, with the input value wrapped as part of the event, while onChangeText sends only the input value.
TextInput is a Core Component that allows the user to enter text. It has an onChangeText prop that takes a function to be called every time the text changed, and an onSubmitEditing prop that takes a function to be called when the text is submitted.
You cannot supply or mutate the props
that have already been defined by the documentation.
Therefore you can create custom component for TextInput
as
const TextInputComponent = ({value, onChangeText, name, ...props}) => (
<TextInput
value={value}
onChangeText={(value) => onChangeText(name, value)} //... Bind the name here
{...props}
/>
)
Usage as you would use normally
onChangeValue = (name, value) => {
console.log(name, value)
// Set the state according to your needs here
}
<TextInputComponent
value={this.state.value}
onChangeText={this.onChangeValue}
name={'Pritish'}
/>
Or you can simply do:
<TextInput
keyboardType='numeric'
maxLength={4}
onChange={e => this.handleChange(e,'foo')}
/>
<TextInput
name='bar'
maxLength={4}
onChange={e => this.handleChange(e,'bar')}
/>
and then in ts file
handleChange(event,name){
// whatever
}
Edit: If you are worried about performance, you can use datasets. Any attribute prepended by data-
are added to target.dataset
object.
<TextInput
data-name='foo'
keyboardType='numeric'
maxLength={4}
onChange={this.handleChange}
/>
<TextInput
data-name='bar'
maxLength={4}
onChange={this.handleChange}
/>
and then in ts file
handleChange(event){
const {name} = event.target.dataset
// whatever
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With