Reputation: 10350
In my React Native 0.70 app, there are 2 components Home
(parent) and ListSearch
(child). Users enter server string in Home
and search result is displayed in ListSearch
. When users click navigation.goBack()
on ListSearch
to go back to Home
, useFocusEffect
from react navigation 6.x is used to reset the placeholder on search bar in Home
. Here is the code in Home
(parent) to reset the placeholder:
export default Home = ({ navigation}) => {
const searchHolder = "Enter search string here";
const [plcholder, setPlcholder] = useState(searchHolder);
const submitsearch = async () => {
...
setPlcholder(searchHolder);//reset place holder
navigation.navigate("ListSearch", {artworks:res, title:"Search Result"}). //<<==ListSearch is component of result displaying
}
//reset placeholder whenever the Home is focused.
useFocusEffect(
React.useCallback(() => {
setPlcholder(searchHolder); // reset the place holder search bar
},[navigation])
);
//view
return (
...
<View style={{flex:5}}>
<TextInput style={{fontSize:hp("3%")}} placeholder={plcholder} onChangeText={strChg}></TextInput>. //plcholder here
</View>
)
}
The code above didn't work. When users navigation.goBack()
to Home
component, the placeholder in search bar was the previous search string and was not updated.
Upvotes: 0
Views: 663
Reputation: 215
Placeholder string is updated when you navigate to ListSearch
, You should set value
of TextInput to empty string, here is the code you can refer,
import { useState,useEffect } from 'react';
import { View, TextInput, TouchableOpacity, Text } from 'react-native';
export default Home = ({ navigation }) => {
const searchHolder = 'Enter search string here';
const [plcholder, setPlcholder] = useState(searchHolder);
const [text, setText] = useState();
const submitsearch = () => {
console.log('submitsearch called ', searchHolder);
setText("");
setPlcholder(searchHolder);
navigation.navigate('ListSearch');
};
//view
return (
<View style={{ flex: 5 }}>
<TouchableOpacity onPress={() => submitsearch()}>
<Text>Submit</Text>
</TouchableOpacity>
<TextInput
style={{ fontSize: 20, marginTop: 30 }}
placeholder={plcholder}
value={text}
onChangeText={(val) => setText(val)} />
</View>
);
};
Here is the demo, I've created.
Upvotes: 1