Search code examples
react-nativereact-navigationreact-propsreact-navigation-v5

React-native, passing a param through navigation v4 to navigation v5


I know only a little about to get a param in react-navigation v5, then I'd like to know how I can transform this file "ShowScreen.js v4 into a ShowScreen.js v5

This is my file using react-navigation v4:

import React, { useContext } from 'react';
import { View, Text, StyleSheet } from 'react-native';
import { Context } from '../../context/BlogContext';

export default function ShowScreen({ navigation }) {
  const { state } = useContext(Context);

  const blogPost = state.find(
    blogPost.id === navigation,getParams('id')
  );

  return (
    <View style={styles.container}>
      <Text>{blogPost.title}</Text>
    </View>
  );
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    justifyContent: 'center',
    alignItems: 'center'
  }
});

But I know that if I want to use something like the react-navigation v5, I need to change it in a new way because there's no getParam in react-navigation v5, the documentation shows a different way, but I'm not sure how I can use it in my two different screens

This is the screen Context where the param id is located using react-navigation v4:

import createDataContext from './createDataContext';

const blogReducer = (state, action) => {
  switch (action.type) {
    case 'delete_blogpost':
      return state.filter(blogPost => blogPost.id !== action.payload);
    case 'add_blogpost':
      return [
        ...state,
        {
          id: Math.floor(Math.random() * 99999),
          title: `Blog Post #${state.length + 1}`
        }
      ];
    default:
      return state;
  }
};

const addBlogPost = dispatch => {
  return () => {
    dispatch({ type: 'add_blogpost' });
  };
};
const deleteBlogPost = dispatch => {
  return id => {
    dispatch({ type: 'delete_blogpost', payload: id });
  };
};

export const { Context, Provider } = createDataContext(
  blogReducer,
  { addBlogPost, deleteBlogPost },
  []
);

I have no idea what's the right way to send the user from the post with the id generated to the right screen generated with the same id, but I know the state is also not used in react-navigation v5...


Solution

  • React Navigation 5 has a completely new component-based API. While the main concepts are the same, the API is different, you have multiple options:

    1. Reuse code using the old API with minimal changes, you can use the compatibility layer.
    2. You could watch this tutorial it short and descriptive.
    3. Read the documentation, as it is fast and clear.