Reputation: 520
Maybe my question doesn't match. How to change the value of a variable using another component? I want to use react-hooks to change value like redux.
For example, I have variable const [message, setMessage] = useState('');
,that location in SearchScreen.js
file. And I want to change value of this variable in Test.js
file.
//SearchScreen file
import 'react-native-gesture-handler'
import React,{ useState } from 'react';
import {View, Text, Button} from 'react-native';
const SearchScreen = ({navigation}) =>{
const [message, setMessage] = useState('');
return(
<View>
<Text>{message}</Text>
<Button
title='enter to next bar'
onPress={() => navigation.navigate('Test')}
/>
</View>
);
};
export default SearchScreen;
and another file
//Test file
import React,{useState} from 'react';
import {View, Text} from 'react-native';
const Test = () =>{
return(
<View>
<Text>
</Text>
</View>
);
};
export default Test;
Can I write immediately setMessage('Testing')
in Test.js
file
Upvotes: 0
Views: 463
Reputation: 4252
Send CallBack for setMessage value message through navigation
import React,{ useState } from 'react';
import {View, Text, Button} from 'react-native';
const SearchScreen = ({navigation}) =>{
const [message, setMessage] = useState('');
return(
<View>
<Text>{message}</Text>
<Button
title='enter to next bar'
onPress={() => navigation.navigate('Test',{setMessage})}
/>
</View>
);
};
export default SearchScreen;
after that get this callback from navigation props like in you test route
Test file
import React,{useState} from 'react';
import {View, Text} from 'react-native';
const Test = (props) =>{
const {navigation} = props;
const setMessage = navigation.state.params.setMessage;
return(
<View>
<Text>
</Text>
</View>
);
};
export default Test;
for documentation check send value to other screen
Upvotes: 1