Reputation: 95
I have code for a custom TextInput component and I want to use this component for both a username and password value for a login screen, however, I don't know how to retrieve the value of the text input for a specific instance.
import React from 'react';
import { TextInput, StyleSheet, View, ImagePropTypes } from 'react-native';
const TextInputCustom = (props) => {
const [value, onChangeText] = React.useState();
return (
<View style={styles.container}>
<TextInput
placeholder={props.name}
style={styles.textInput}
onChangeText={text => onChangeText(text)}
value={value}
/>
</View>
);
}
After Importing I created in my login screen
<TextInputCustom name="Username"/>
<TextInputCustom name="Password"/>
How do I get the value so that I can assign it to a variable for each TextInputCustom instance?
Upvotes: 1
Views: 2937
Reputation: 2045
You need to move the value
and onChange
to the parent level:
import { TextInput, StyleSheet, View, ImagePropTypes } from 'react-native';
const TextInputCustom = (props) => {
const {value, onChange} = props;
return (
<View style={styles.container}>
<TextInput
placeholder={props.name}
style={styles.textInput}
onChangeText={text => onChange(text)}
value={value}
/>
</View>
);
}
And then use it like this:
<TextInputCustom name="Username" value={username} onChange={onUsernameChange} />
<TextInputCustom name="Password" value={password} onChange={onPasswordChange} />
This is the practice that is used in general for simple components. You don't need to handle the value in the component level, but in the component that is using your custom component.
Upvotes: 3