Phumu Mahandana
Phumu Mahandana

Reputation: 95

React native navigate to ID of specific post

I would like to navigate the same way you do with react-router. I am fetching an API and display the results as cards, when you click a card, I need it to navigate to a specific ID based on the card selected.

<Route path='/item:id' component={item-details} />

and then on the card, you do this.<Link to='item/:id' > Card...</Link>

That's how you do it with react-router-dom...I need to archive the same with React Native. Any solutions?

Upvotes: 2

Views: 6184

Answers (1)

Tom Oakley
Tom Oakley

Reputation: 6403

I suggest using react-navigation, it's the best solution for navigation for a RN app. It's not quite like React Router but RN requires a different method. In react-navigation, you declare your screens as 'navigators', e.g stack navigator.

import { createStackNavigator } from '@react-navigation/stack';

const Stack = createStackNavigator();

function MyStack() {
  return (
    <Stack.Navigator>
      <Stack.Screen name="Screen1" component={Screen1Component} />
      <Stack.Screen name="Screen2" component={Screen2Component} />
    </Stack.Navigator>
  );
}

On each screen, a navigation prop is passed down. This has a lot of properties and functions but one is a function called navigate, which takes you to another screen in your stack. For example:

const Screen1Component = ({ navigation }) => (
  <View>
    // content 
    <TouchableOpacity onPress={() => navigation.navigate('Screen2) })>Go to Screen2</TouchableOpacity>
  </View>
)

navigate also has a second parameter it can take called screen params. These are parameters you can pass between screens when you navigate. It's used like navigation.navigate('Screen2, { id: '1234' }).

In your Screen2 component, there will be a route prop, where you can then pick that param up and use it, for example:

const Screen2Component = ({ route, navigation }) => {
  const { id } = route.params
  // do something with it, call api, pass to redux action,etc

  return ...
}

Hope that helps.

Upvotes: 3

Related Questions