useRoute
useRoute is a hook which gives access to route object. It's useful when you cannot pass down the route object from props to the component, or don't want to pass it in case of a deeply nested child.
It can be used in two ways.
Getting the route object by screen name
The hook accepts the name of the current screen or any of its parent screens to get the corresponding route object:
- Static
- Dynamic
import { useRoute } from '@react-navigation/native';
function MyText() {
const route = useRoute('Profile');
return <Text>{route.params.caption}</Text>;
}
import { useRoute } from '@react-navigation/native';
function MyText() {
const route = useRoute('Profile');
return <Text>{route.params.caption}</Text>;
}
Getting the current route object
You can also use useRoute without any arguments to get the route object for the current screen:
function MyComponent() {
const route = useRoute();
return <Text>{route.name}</Text>;
}
This is often useful for re-usable components that are used across multiple screens.
See the documentation for the route object for more info.
Using with class component
You can wrap your class component in a function component to use the hook:
class MyText extends React.Component {
render() {
// Get it from props
const { route } = this.props;
}
}
// Wrap and export
export default function (props) {
const route = useRoute('Profile');
return <MyText {...props} route={route} />;
}