I have the following code which creates a simple stack navigator for 2 components Login
and List
. I have a useState
hook in the file with the navigator (App.js
) and I want to pass down the setter and getter to each of the screens. I have tried using screenProps
on the stack navigator but after logging the props passed to each of the components, the variables do not appear.
TL;DR I need to pass props from the Stack.Navigator
down to each screen
<NavigationContainer>
<Stack.Navigator screenProps={{setVariable, variable}}>
<Stack.Screen
name="Login"
component={Login}
options={navOptions}
/>
<Stack.Screen
name="List"
component={List}
options={navOptions}
/>
</Stack.Navigator>
</NavigationContainer>
You need to use React's context API
// MyContext.js
export const MyContext = React.createContext();
// App.js
const context = React.useMemo(() => ({
setVariable,
variable
}), [variable]);
return (
<MyContext.Provider value={context}>
<NavigationContainer>
<Stack.Navigator>
<Stack.Screen
name="Login"
component={Login}
options={navOptions}
/>
<Stack.Screen
name="List"
component={List}
options={navOptions}
/>
</Stack.Navigator>
</NavigationContainer>
</MyContext.Provider>
);
// Home.js
const variable = React.useContext(MyContext);
https://reactnavigation.org/docs/en/upgrading-from-4.x.html#global-props-with-screenprops