jamesrogers93
jamesrogers93

Reputation: 411

Passing props to components in React Navigation v5 dynamic component configuration

In my app, I am displaying a login screen if the user is not logged in, and a logged-in screen if the user is logged in. In the simple example below, you can see that I am checking if the jwt and user exists in my redux store and then displaying the appropriate screen.

type Props = {
    +jwt: string | null;
    +user: UserModel | null;
};

export class AuthStackNavigator extends Component<Props> {

    renderScreen() {

        if (this.props.jwt && this.props.user) {
            return (
                <Stack.Screen name={'AuthenticatedView'} component={AuthenticatedView} />
            );
        } else {
            return (
                <Stack.Screen name={'LoginView'} component={LoginView} />
            );
        }
    }

    render() {
        return (
            <Stack.Navigator>
                {this.renderScreen()}
            </Stack.Navigator>
        );
    }
}

const mapStateToProps = (state) => {
    return {
        jwt: getJwt(state),
        user: getUser(state)
    };
};

export default connect(mapStateToProps)(AuthStackNavigator);

You can see that the AuthenticatedView component is rendered if the jwt and user exists. Inside AuthenticatedView, I am currently getting the user from the redux store again where it is possibly null - this involves another check. Is there a way I can pass the user to the component as a prop from <Stack.Screen> as I know it exists here? This way I do not have to make the same check multiple times.

I'm aware that you can send data to components when navigating using:navigation.navigate('View', props), but I do not navigate to this screen using this function.

Upvotes: 3

Views: 5179

Answers (1)

satya164
satya164

Reputation: 10145

Read the official documentation https://reactnavigation.org/docs/hello-react-navigation/#passing-additional-props

Upvotes: 5

Related Questions