Home > Enterprise >  How do I pass state variables from one screen to another in a React Native Project?
How do I pass state variables from one screen to another in a React Native Project?

Time:01-28

My state variables are defined as follows:

const [email, setEmail] = useState('');
const [password, setPassword] = useState('');

Both of these values are being updated via user input as follows:

 <View style={styles.inputContainer}>
            <TextInput
              style={styles.input}
              returnKeyType="next"
              onSubmitEditing={() => {
                passWord.current.focus();
              }}
              blurOnSubmit={false}
              placeholder="Email Address"
              placeholderTextColor={'gray'}
              value={email}
              onChangeText={text => setEmail(text)}
            />
          </View>

I want to have access to the email and password variables on a different screen but cannot seem to figure out which hook works best in this scenario. How would I go about this problem?

CodePudding user response:

I am not sure if you're using navigation.navigate but if you are you can use it as shown on the docs seen here.

Basically, after you pass the component you're trying to reach, you would pass an object containing the data you want. On the other end, you would gather that back up using route.params and the key/name you gave it when calling navigate.

My own example can be seen below:

<TouchableOpacity
    style={styles.button}
    onPress={() => {
        navigation.navigate('TicketPurchase', {tickId: 'rollingstones'});
    }}>
    <Text style={styles.ticketbutton}>BUY TICKETS</Text>
</TouchableOpacity>

It was pulled in the other component as seen here: const {tickId} = route.params;

  • Related