I’ve four screens in a Stack navigator in Books.js
:
function Books(props) { return ( <Stack.Navigator> <Stack.Screen name="Home" component={BooksMenu} /> <Stack.Screen name="Order Book" component={BookOrder} /> <Stack.Screen name="My Books" component={MyBooks} /> <Stack.Screen name="Details" component={MyBooksDetails} /> </Stack.Navigator> ); }
From the BooksMenu
screen user is navigating to the MyBooks
screen and from the MyBooks
there is a button that navigates the user to MyBooksDetails
screen.
This error pops-up with I click on the button that is supposed to navigate the user to MyBooksDetails
from the MyBooks
screen. This is how the button action is handled:
<TouchableWithoutFeedback style={styles.detailsBtn} onPress={() => navigation.navigate('Details')} > <Text style={styles.detailsBtnText}>See Details</Text> </TouchableWithoutFeedback>
I’ve restructured the default props
with this on BookCell
which is just a custom component in the MyBooks
screen.
function BooksCell({ navigation }) {...
The screen which has the BookCell
component still has default props
.
function MyBooks(props) {...
So the sub screen (which is the component BooksCell
) has navigation
as a restructured prop and its parent screen MyBooks
as default props
and the parent screen of MyBooks
which is BooksMenu
also have navigation
as a restructured prop.
function BooksMenu({ navigation }) {...
Hope this makes sense. I’m new to react native so I have an idea that might be wrong but not sure how to fix it.
Advertisement
Answer
The destructuring of ({navigation})
vs. (props)
does not make a difference. The important thing is what props are provided when the component is called.
Writing ({navigation})
means that your component expects to be called with a navigation
prop. It doesn’t provide that prop.
The top-level screens such as MyBooks
and BooksMenu
will be called with the props navigation
and route
when they are rendered by the Navigator. BooksCell
is not a screen so React Navigation will not provide it with any props.
If you want to use the prop navigation
in BooksCell
then you must provide it. You can pass it down from a parent which has the prop.
function MyBooks(props) { ... return ( <BooksCell navigation={props.navigation} /> ); }
The other option is to access navigation
in BooksCell
through the useNavigation()
hook, which gets the navigation
object by using the current Navigator’s context.
function BookCell() { const navigation = useNavigation(); ... }