Can't change value in Input field in React Native? - react-native

I have set a value in useState but whenever I change my value in input field I am not able to change every character which I enters. It's like when I input any character after Beckham in the field it gets deleted. Nor I can't delete beckham.
But if I use this like const [name, setName] = useState("Beckham"); I am able to change value in field.
Is it happening because I have set a value in useState ??
const [disable, setDisable] = useState(true);
const [name, setName] = useState("Beckham");
return(
<Text style={{ marginLeft: 10, color: 'darkgrey' }}>Full Name :</Text>
<View style={{ flexDirection: 'row' }}>
<View style={{ width: (Dimensions.get('window').width) - 50 }}>
<Input placeholder='Name' value={name} disabled={disable} onChangeText={ () => setName(name)}/>
</View>
<View>
<MaterialCommunityIcons style={{ marginTop: 10 }} name='grease-pencil' size={24} color='black' onPress={() => setDisable(!disable)} />
</View>
</View>
);

You should send the new text in the function call so you can change the name state
`onChangeText={(text)=> setName(text)}`

You have to specify the param name in the
onChangeText
onChangeText = {(name) => setName(name)}
And also use TextInput instead of Input
<TextInput
placeholder="Name"
value={name}
disabled={disable}
onChangeText={(name) => setName(name)}
/>

We have to set the enteredValue in the state value to update the text in text input.
Have a try with below code:
const [disable, setDisable] = useState(true);
const [name, setName] = useState("Beckham");
return(
<Text style={{ marginLeft: 10, color: 'darkgrey' }}>Full Name :</Text>
<View style={{ flexDirection: 'row' }}>
<View style={{ width: (Dimensions.get('window').width) - 50 }}>
<Input
placeholder='Name'
value={name}
disabled={disable}
onChangeText={(enteredText) => setName(enteredText)}
/>
</View>
<View>
<MaterialCommunityIcons
style={{ marginTop: 10 }}
name='grease-pencil'
size={24}
color='black'
onPress={() => setDisable(!disable)}
/>
</View>
</View>
);

When you call setName(name) it doesn't change anything because name is state. You can use this.
onChangeText={setName}

Related

React-Native unable to type in TextInput

I'm learning react-native, currently learning state.
I have a TextInput on my screen:
however, when I try to type in it the text doesn't appear.
My code:
const Login = ({ navigation } : any) => {
const [text, setText] = useState('');
return (
<View style={[styles.container, { flexDirection: "column" }]}>
<View style={{ flex: 1, alignItems:"center", justifyContent:"center" }}>
<Image source={require('../assets/images/help.png') } style={{ width: 40, height: 40 }} />
</View>
<View style={{ flex: 2, backgroundColor: "#5f6364", borderTopRightRadius:20, borderTopLeftRadius:20 }}>
<TextInput style={styles.input} placeholder="Type here to translate!" onChangeText={newText => setText(newText)} defaultValue={text} />
</View>
</View>
)
}
Can someone explain why this is happening?
Try replacing the defaultValue with value or remove it completely

Define height of AutoComplete list - React Native

The listStyle where I set the height of my list it's not working on Autocomplete.
I'm using react-native-autocomplete-input.
Check the Example:
<HideKeyboard>
<SafeAreaView style={mainStyle.container}>
<StatusBar style="light" backgroundColor="#0a3f88" />
<SimpleLineIcons style={mainStyle.menuIconHome} name="menu" size={28} color="black" onPress={() => {Keyboard.dismiss(), navigation.openDrawer()}}/>
<Image style={mainStyle.logo} source={logo}></Image>
<Autocomplete
style={{
backgroundColor:"transparent",
textAlign:"center",
}}
onChangeText={(text) => searchFilterFunction(text)}
data={filteredDataSource}
placeholder="Nome da empresa..."
autoFocus={true}
listStyle={{
maxHeight:20,
}}
containerStyle={{
paddingHorizontal:40,
position:"absolute",
top:"45%",
alignSelf:"center",
}}
inputContainerStyle={{
height:40,
zIndex:999,
}}
flatListProps={{
keyExtractor: (item, index) => index.toString(),
renderItem: ({ item }) =>
<TouchableOpacity
onPress={()=>{
navigation.navigate("Projeto",{
item:item,
});
}}
>
<View style={{
height:50,
borderBottomWidth:0.4,
}}>
<Text style={{
color:"#0a3f88",
fontWeight:"bold",
marginLeft:10,
}}>{item}</Text>
</View>
</TouchableOpacity>
}}
/>
<Image style={mainStyle.cmlagos} source={camaraLagos}></Image>
</SafeAreaView>
</HideKeyboard>
As you can see in the prinscreen below , the listStyle have no effect.
Already tried to use ScrollView outside of the Autocomplete but it's the same.
Any suggestions ?
Solved!
Instead of use the listStyle, we can use style:{height: 150} inside of flatListProps.

React native password show hide

I need to show hide my password on eye click.
Right now I am trying to do like this
const [showPassword, setShowPassword] = useState(false)
<View style={styles.SectionStyle}>
<Text style={styles.textStyle} >Password</Text>
<View style={{ flexDirection: 'row', alignItems: 'center' }}>
<TextInput
style={styles.inputStyle}
onChangeText={password => setPassword(password)}
underlineColorAndroid="#FFFFFF"
placeholderTextColor="grey"
secureTextEntry={showPassword}
placeholder="Must be at least 6 characters"
// ref={ref => {
// this._addressinput = ref;
// }}
// onSubmitEditing={Keyboard.dismiss}
blurOnSubmit={true}
/>
<TouchableOpacity onPress={() => setShowPassword(showPassword = !showPassword)}>
<Image
source={require('./../../../public/icons/Hide.png')}
style={{
position: 'absolute',
right: 0,
top: -2,
marginRight: 16,
// marginTop: 30,
width: 16,
height: 16
}}
/>
</TouchableOpacity>
</View>
</View>
But it's not working I am doing something wrong? I think need to do something in state?
the setShowPassword accepts an arrow function as arguments with the state as params
So it should be like this:
<TouchableOpacity onPress={() => setShowPassword(showPassword => !showPassword)}>

How do I prevent data in all other component views on a page from being cleared(rerendering) whenever I start to enter data in other view components?

On a gallery page, I have a text input field that allows the user to describe the kind of pictures and submit or share with a friend.
When I start to type in the text input field, the images in the gallery are cleared(the page re-renders) and all other input fields or component holding data are cleared.
I need help, how to prevent all data from other components from getting cleared whenever I start to enter data in view component on the page.
I am using functional components in my react native app.
export default function EvidenceSubmission ({route, navigation,navigation:{setParams}}){
//Incidence
const [state, setState]= useState({
selectedIncidence: 'select incidence',
photos:[],
});
/**
*clears images in async storage
*/
const clearStorage= async() =>{
try{
await AsyncStorage.clear();
} catch(exception){
console.log('error clearing items');
}
console.log('items cleared (Evidence Page)');
}
useEffect(()=> {
/*Get images from async storage*/
const getData = async () => {
try {
const value = await AsyncStorage.getItem('photos')
if(value !==null){
setState({
photos: (JSON.parse(value)).reverse(),
})
}
}catch(e){
console.log('error with async getData');
}
}
getData();
}, []);
/navigates to photo preview page/
const navigateToPhotoPreview = (path) =>{
navigation.navigate('PhotoPreviewer',
{
transferredImageItem: path,
})
}
return(
<SafeAreaView style= {globalStyle.MainContainer}>
<StatusBar barStyle="light-content" backgroundColor="#174060"/>
<View flexDirection='column' flex={0.456} marginTop={30}
marginRight ={5}
marginLeft ={5}
borderWidth={0.5}
borderRadius={3}
borderColor='#7E7E7E'>
<View>
<FlatList
data= {state.photos}
keyExtractor={(item, index)=> index}
renderItem={ ({ item}) => (
<TouchableOpacity onPress={() => navigateToPhotoPreview(item) }>
<Image
style={{ width:70, height:75,margin:0.5, resizeMode:'cover'}}
source = {{ uri: "file://"+ item}}
// source = {{ uri: item}}
//source = {{ uri: item.node.image.uri}}
/>
</TouchableOpacity>
)
}
numColumns = {5}
/>
</View>
</View>
<TouchableOpacity style={styles.addPhotoButton}
onPress={()=>{navigation.goBack()}}>
<Add
name={'add'}
size={30}
color="white"
/>
</TouchableOpacity>
<View style={{justifyContent: 'center', margin:5 ,flex: 1.2}}>
<View style={{borderWidth: 1,
borderColor:'#C4C4C4',
borderRadius:5,
width: 270,
marginLeft: 5,
marginBottom: 0,
marginTop: 15}}>
<Picker
selectedValue ={state.selectedIncidence}
style={{height:45, width: 270,
fontFamily:'roboto',
fontStyle:'normal',
fontWeight:'normal'}}
onValueChange={(itemValue, itemIndex) =>
setState({selectedIncidence: itemValue})
}
>
<Picker.Item label="Non-Compliance" value="Non-Compliance"/>
<Picker.Item label="Logistics" value="Logistics"/>
<Picker.Item label="Harassment" value="Harassment"/>
</Picker>
</View>
<View marginBottom={0} marginLeft={5} marginTop={15}>
<Text style={styles.textStyle}>
Description
</Text>
</View>
<View style={{flexDirection:'row'}} >
<View>
<TextInput
style={{height: 70,
width: 270,
borderRadius: 8,
borderColor:'#C4C4C4',
borderWidth: 1, marginLeft: 5}}
onChangeText={(text) => setState({text})}
value={state.text}
multiline={true}
enablesReturnKeyAutomatically={true}>
</TextInput>
</View>
<TouchableOpacity style={styles.microphoneButton}>
<Microphone name="microphone"
size={21}
color='white'
/>
</TouchableOpacity>
</View>
<View marginBottom={0} marginLeft={0} marginTop={15} marginBottom={15} >
<View style={{flexDirection: 'row'}}>
<Text style={{margin:10,marginRight:20,
fontFamily:'roboto', fontSize: 14,
fontWeight:'bold',
}}>
Submit as
</Text>
<View style={styles.radioCircumference}>
<TouchableOpacity style={styles.radioButton}></TouchableOpacity>
</View>
<Text style={{marginLeft: 5, marginRight: 0, marginTop: 10}}>anonymous</Text>
<Text style={{marginLeft: 10, marginRight: 10, marginTop: 10, fontWeight:'bold'}}> or </Text>
<View style={styles.radioCircumference}>
<TouchableOpacity style={styles.radioButton}></TouchableOpacity>
</View>
<Text style={{marginTop: 10,marginLeft: 5, marginRight: 0}}>Sign In</Text>
</View>
</View>
<TouchableOpacity
style={styles.button}
onPress={()=>clearStorage()}
>
<Text style={{color:'white',
alignSelf:'center',
fontSize: 18,
}}>
Next
</Text>
</TouchableOpacity>
</View>
</SafeAreaView>
);
}
Ok, so the first issue here is that you are mutating the state of setState. You are using the same state for your TextInput and Picker components. There are two ways to go about this.
1.Using the same state as u are doing.
const [formState, setFormState] = useState({
selectedIncidence: 'select incidence',
text: "",
photos: [],
});
In this case, when your onChangeText and onValueChange will be
onValueChange = {
(itemValue, itemIndex) =>
setFormState(formState => ({
...formState,
selectedIncidence: itemValue
}))
}
onChangeText = {
(text) => setFormState(formState => ({
...formState,
text
}))
}
2.The second approach is to use different states for each field.
const [selectedIncidence, setSelectedIncidence] = useState('select incidence');
const [text, setText] = useState("");
const [photos, setPhotos] = useState([]);
In this case, when your onChangeText and onValueChange will be
onValueChange = {
(itemValue, itemIndex) =>
setSelectedIncidence(itemValue)
}
onChangeText = {
(text) => setText(text)
}
I hope you find this helpful.

React native TextInput isFocused method

I want to change background image dynamically.I tried to know TextInput is focused or not with this way.Also I tried this.text.current.isFocused().But It didn't help me.Anyone knows?
text={};
renderDrawerContent(){
let image = this.text.isFocused() ? require('../assets/images/gyzyl.png') : require('../assets/images/BlackBack.jpg');
return(
<Container style={styles.containerDrawer}>
<ImageBackground
source={image}
style={{flex:1}}
resizeMode={'cover'}
>
<Content style={{ paddingTop: 0, }}>
<View style={{paddingTop: 20}}>
<View style={{flexDirection:'column' , marginVertical:5 ,padding:15}}>
<Text style={styles.search}>Search</Text>
<TextInput ref={ref => this.text=ref} autotFocus={this.state.Focused} underlineColorAndroid={'white'} placeholder='Cinema, Theatre, Concert ...' placeholderTextColor = '#fff' style={{color: '#fff', fontSize: 16 ,flex:1 , borderBottomColor: '#fff'}} />
</View>
</View>
</Content>
</ImageBackground>
</Container>
);
}
You can use the onFocus event from textinput to do this along with onBlur.
Using this method you should add to your state object a value that tracks if the input is focused.
<TextInput onFocus={()=> this.setState({inputFocused: true})} onBlur={()=> this.setState({inputFocused: false})}/>
then just use your inputFocused to check if the input is focused or not
An alternative that I got success.
const [themeInput, setThemeInput] = useState(false)
<TextInput
mode='outlined'
theme={{colors: {primary: `${colors.salmon}`, }}}
onFocus={() =>setThemeInput(true)}
onBlur={() =>setThemeInput(false)}
label="Email"
left={ <TextInput.Icon
name={() => <Feather name='mail' size={26}
color={ themeInput ? colors.salmon : colors.gray3} />} />}
/>