(I’m a total beginner so I’m just trying to understand react) I’ve created an textinput and username/setUsername state that I want to save in a different component screen. By some reason I can’t make it work, I’ve deleted all my tries and just posted the current code, can someone please guide me?
Start.js
const [username, setUsername] = useState("")
const changeHandler = (val) => {
setUsername(val)}
const buttonPress = ()=> {
console.log(username)
navigation.navigate("Main")}
return (
<SafeAreaView style={styles.container}>
<Text style={styles.text}>Enter name here</Text>
<View style={styles.textinputarea}>
<TextInput
style={styles.textinput}
placeholder="Name here"
maxLength = {12}
onChangeText = {changeHandler}
/>
<TouchableOpacity onPress={buttonPress}>
<Ionicons name="checkmark-circle" size={40} color="white"/>
</TouchableOpacity>
</View>
</SafeAreaView>
);
}
And here is the part in Profile.js where I want to update the state when the "user" submits their name in Start.js
<TouchableOpacity>
<Title style={styles.text}>Hello {username}!</Title>
</TouchableOpacity>
>Solution :
This article is about sharing state between different components without any complex React Context/Redux techniques.
So it is good for beginners! Short and informative.
You will need to have a component that will be responsible for rendering the Start and Profile components. Let’s say, an App.js or any other component ( Layout.js ).
Move
const [username, setUsername] = useState("")
to the Layout.js / App.js, and pass it down as a prop like
<Start username={ username } setUsername={ setUsername } />
Also pass value prop to the TextInput component.
So that state that gets updated by onChangeText actually updates the input’s value., not only the state variable, but the component.
<TextInput
value={ username }
style={styles.textinput}
placeholder="Name here"
maxLength = {12}
onChangeText = {changeHandler}
/>