I create two TouchableOpacity
in React Native
. Code.
const App = () => {
const notification = [
{ id: 1, name: 'David Silbia', message: 'Invite Jo Malone London’s Mother’s', time: 'Just now' },
{ id: 2, name: 'Adnan Safi', message: 'Started following you', time: '20 min ago' },
{ id: 3, name: 'Ronald C. Kinch', message: 'Like you events', time: '9 hr ago' },
{ id: 4, name: 'Clara Tolson', message: 'Join your Event Gala Music Festival', time: 'Wed, 3:30 pm' },
]
return (
<View style={{flexDirection:'row'}}>
<TouchableOpacity
style={[styles.BellButton,{marginRight: 8,width: 50,}]}
onPress={() => navigation.navigate("Notification", {item:notification})}>
</TouchableOpacity>
<TouchableOpacity style={styles.BellButton}
onPress={() => navigation.navigate("Notification")}>
</TouchableOpacity>
</View>
)
}
export default App
On press 1st TouchableOpacity, it move to Notification page
with notification data
.
On press 2nd TouchableOpacity, it just move to Notification page
.
Notification page:
const Notification = ({ route }) => {
const navigation = useNavigation();
const { item } = route.params;
console.log(item)
return ()
}
export default Notification
The problem is I want to only send notification data
by pressing 1st TouchableOpacity
and on press 2nd TouchableOpacity
, it move to Notification page
and data is present there.
2
Answers
I solved my problem. The code is:
App
Notification
With the above code, I assume that you are using React Navigation.
Firstly, ensure that you do not define the initialParams because it will be merged with whatever you passed to the screen. Please refer to this: https://reactnavigation.org/docs/params#initial-params
Secondly, with the Native Stack Navigator, it behaves a bit differently than assumed: it will navigate back to the existing screen if the screen exists in the stack, determined by comparing the screen’s name. To create a new screen with new params (empty value, in your case), you need to customize the getId prop as guided here: https://reactnavigation.org/docs/navigation-prop#navigate
Thirdly, it is considered an anti-pattern to pass data, such as your example, as navigation params. It would be better to use some form of a store to update/retrieve data, like Redux. Whenever the new page is loaded, it can then load data from the store based on minimum required params, such as {isEmpty: true}.