Search code examples
react-nativenavigationscreenpass-dataonpress

How to pass data between 2 Screen and not use navigation in react native


I have 2 screens and I want to pass data from first screen to second screen without using navigation, because when using navigation it is required to go to next screen, I only want when I click a button from the first screen then the data will be transferred to the second screen. Same problem, is it possible to transfer data from second screen to first screen when pressing back button to return to first screen, I use default back button from navigation so don't know how to call onPress() of that back button.


    export default function FirstScreen({ navigation }) {
    return (
        <View>
            <TouchableOpacity onPress={() => {/* pass data (for example text) to SecondScreen 
        and don't need to switch to the SecondScreen */}}>
                <View>
                    <Icon name="close"></Icon>
                </View>
            </TouchableOpacity>
            <TouchableOpacity onPress={() => { navigation.navigate('secondscreen') }}>
            </TouchableOpacity>
            <Text>{/* display the data sent from the SecondScreen */}</Text>
        </View>
    );}

SecondScreen

export default function SecondScreen({ navigation }) {
/* pass data to FirstScreen when click to back button in header navigation*/
return (
    <View>
        <Text>{/* display the data sent from the FirstScreen */}</Text>
    </View>
);}

I have tried searching but still can't find a specific solution for this problem. Hope everybody help please


Solution

  • There are several options, you can use "useState()" and pass the state and setState through props of course, and/or create a callback function with it.

    Unless this is the only place you will use a state like this, it sounds like it would be better to use a global app state in this case, which will store the state temporarily for the current session. At the same time that state would be readable and accessible from your whole application.

    I believe Redux is the most popular way of handling global state in an application right now, you should google it and do some research.