waffl
waffl

Reputation: 5511

React Native: How to pass props in React Navigation

In my React Native application, I am using react-navigation and have a class component using react-native-webview:

<WebView source={{ uri: this.props.url }} />

This is implemented in a StackNavigator like so:

<Stack.Navigator>
  <Stack.Screen name="Viewer" component={WebViewScreen} />
</Stack.Navigator>

How can I used React Context to pass a url prop to the WebViewScreen component?

Looking at the react-navigation docs, it mentions an alternative:

<Stack.Screen name="Home">
  {props => <HomeScreen {...props} extraData={someData} />}
</Stack.Screen>

but with caveats, so I would like to try to use context. Ideally, I would be able to push to the stack and point the WebViewScreen to any url:

this.props.navigation.push('Viewer', {
    route: 'https://www.example.com'
})

Upvotes: 0

Views: 1066

Answers (2)

bas
bas

Reputation: 15722

If you only care about the value changing on a navigation action to a screen where your Webview lives, you can simply access the data you passed on navigation via the route prop:

const route = this.props.route.params?.route ?? 'default url';

<WebView source={{ uri: route }} />

Source: https://reactnavigation.org/docs/upgrading-from-4.x/#no-more-getparam

Upvotes: 1

Sheldon Oliveira
Sheldon Oliveira

Reputation: 1005

Add the provider and get the value in your component.

const MyContext = React.createContext();

<MyContext.Provider value={{url: '/somethig'}}>
  <Stack.Navigator>
    <Stack.Screen name="Viewer" component={WebViewScreen} />
  </Stack.Navigator>
</MyContext.Provider>

In your HomeScreen use the hooks to get your value:

const value = useContext(MyContext);

Upvotes: 0

Related Questions