Home > database >  React Native Typescript, pass variable to another screen
React Native Typescript, pass variable to another screen

Time:04-03

I cant seem to figure how to pass variable with typescript in react native, I have tried the params but its saying undefined is not an object (evaluating 'navigation.props.value').

below are the codes.

import {useNavigation} from '@react-navigation/core';
const navigation = useNavigation();

.......

<TouchableOpacity onPress={() => navigation.navigate('NewsDetails', {value: 'hi', })}>
                  <Block row flex={0} align="center">
                    <Text
                      p
                      color={colors.link}
                      semibold
                      size={sizes.linkSize}
                      marginRight={sizes.s}>
                      Read Article
                    </Text>
                    <Image source={assets.arrow} color={colors.link} />
                  </Block>
                </TouchableOpacity>

then to display it in screen be this is what I had done but its not working

<Text p marginBottom={sizes.s}>
               {navigation.props.value}
</Text>

CodePudding user response:

React navigation pass variables as params, not props. You can pass it using hooks, but then you will need to use the useRoute hook to get the route in the next screen, then get it as route.params.value

const nextScreen = () => {
  const route = useRoute()

  return <Text>route.params.value</Text>
}

Please notice that you can pass the navigation and route props from the navigator stack, and then you shouldn't need to use hooks:

https://reactnavigation.org/docs/params/

https://reactnavigation.org/docs/use-route

CodePudding user response:

Since NewsDetails is a screen where you can navigate to, it is handled by a navigator, thus the route and the navigation props are passed to this screen by the navigator. You can access this in your NewsDetails component from the screen props directly as follows.

const NewsDetails = ({route}) => {

   const value = route.params.value

   return (...)
}
  • Related