Search code examples
jwtreact-nativereact-propsreact-navigation-v5

React Navigation version 5.x : Passing states and function to all screens


I am trying to configure react navigation in my react native app which has persistent user authorization.

const Stack = createStackNavigator();

export default class App extends Component {
  constructor() {
    super();
    this.state = {
      jwt: '',
      id:'',
      loading: true,
    };
    this.deleteItem = deviceStorage.deleteItem.bind(this);
    this.loadItem = deviceStorage.loadItem.bind(this);
    this.loadItem();
  }

  newJWT = (jwt) => {
    this.setState({jwt});
  };
  newID = (id) => {
    this.setState({id});
  }
 
 componentDidMount(){
    this.loadItem();
  }
  
  render() {
   if (!this.state.jwt) {
      return (
        <NavigationContainer>
          <Stack.Navigator headerMode='null'>
          <Stack.Screen name="Login" component={LoginScreen}/>
          <Stack.Screen name="Signup" component={SignUpScreen}/>
          </Stack.Navigator>
        </NavigationContainer>
      );
    } else {
      return (
        <NavigationContainer>
          <Stack.Navigator headerMode='null'>
           <Stack.Screen name="AuthHome" component={AuthHomeScreen}/>
          </Stack.Navigator>
        </NavigationContainer>
      );
    }
  }
}

I need to pass jwt and user id to all authenticated screens and also pass functions like newJWT to LoginScreen.So I can use that function to update jwt and user id.

I don't want to use React Hooks or Redux for building this app.

  1. I don't know how to pass jwt and id to all authenticated screens
  2. If passed, I need to know how I access jwt,id props inside the LoginScreen ?

Can anyone help me with these questions ?


Solution

  • You could use a React Context Provider in React Native. This prevents the use of props and lets you pass variables and functions through to any component inside of the provider.

    Read more here