I have a question about react native. I want to write a username in the textInput here
function logIn({ navigation }) {
const [username, setUsername] = useState('');
return (
<View style={{ backgroundColor: "white"}} >
<View>
<TextInput style={styles.input} placeholder='username' placeholderTextColor='white' textAlign='center' onChangeText={(val) => setUsername(val)} />
</View>
<View>
<Button title="Go to Home" onPress={() => navigation.navigate('Home')} />
</View>
</View>
);
}
and then I want to see the username i wrote on this screen. Of course this doesnt work because it shows Cant find variable username so is there a way to fix this?
function HomeScreen({ navigation }) {
return(
<View style={{ flex:1, alignItems: 'center', justifyContent: 'center'}}>
<Text>Welcome {username}</Text>
</View>
);
}
You need to structure your state in a way that it is accessible to the components that need it. React likes you to have state in a component thats 'higher' in the tree than the components that need it, you can look at https://reactjs.org/docs/lifting-state-up.html for this.
Otherwise you could use the Context API or a 'global' store like Redux.
Logged in user data is a good candidate for the likes of Context or Redux, that way you will have access to the likes of username in any part of the application that is within your Context / Redux provider that provides the logged in data (or whatever other global data you may have)
You colud pass parameters to Home screen using navigation.navigate function in this way:
function logIn({ navigation }) {
const [username, setUsername] = useState('');
return (
<View style={{ backgroundColor: "white"}} >
<View>
<TextInput style={styles.input} placeholder='username' placeholderTextColor='white' textAlign='center' onChangeText={(val) => setUsername(val)} />
</View>
<View>
<Button title="Go to Home" onPress={() => navigation.navigate('Home', {username: username})} />
</View>
</View>
);
}
Then in HomeScreen:
function HomeScreen({ navigation, route }) {
return(
<View style={{ flex:1, alignItems: 'center', justifyContent: 'center'}}>
<Text>Welcome {route.params.username}</Text>
</View>
);
}