Reputation: 1999
I'm trying to use navigation to navigate and pass props to another component, but for some reason, the props are getting undefined in the destination screen.
I have a main screen with flat list, each item on the flat list moves the user to a second screen with the corresponding data from the list item.
This is the main screen flat list and the navigate function:
async function showConversation(company: Company) {
const currentUser: User = await StorageHelper.retrieveEntity() as User;
const from = currentUser.uid;
const to = company.uid;
console.log(from); <-- logs correctly
console.log(to); <-- logs correctly
navigation.navigate('Conversation', {to: to, from: from});
}
return (
<FlatList<Company>
data={companies}
renderItem={({item}) => (
<TouchableOpacity onPress={() => showConversation(item)}>
<CompanyCard company={item} />
</TouchableOpacity>
)}
keyExtractor={(item) => item.uid}
showsVerticalScrollIndicator={false}
/>
)
This is my Conversation screen:
interface conversationScreenProps {
navigation: any;
to: string
from: string;
}
const ConversationScreen = ({
navigation,
to,
from,
}: conversationScreenProps) => {
const [messages, setMessages] = useState<Array<IMessage>>([]);
const [chatMessage, setChatMessage] = useState<string>('');
const socket = io('http://127.0.0.1:3000');
console.log(to); <-- logs undefined
console.log(from); <-- logs undefined
}
I saw similar questions to this one, but I still couldn't figure out why this is happening.
Upvotes: 0
Views: 57
Reputation: 16334
Params are passed inside the route prop they are not passed as separate prop. You will have to access it like below
const ConversationScreen = ({
navigation,
route
}: conversationScreenProps) => {
const [messages, setMessages] = useState<Array<IMessage>>([]);
const [chatMessage, setChatMessage] = useState<string>('');
const socket = io('http://127.0.0.1:3000');
console.log(route.params.to); <-- logs undefined
console.log(route.params.from); <-- logs undefined
}
You can check the reference here https://reactnavigation.org/docs/params/
Upvotes: 2
Reputation: 325
You should access them like this. Because you are not passing the props directly but through react navigation.
let to = navigation.state.params.to
let from = navigation.state.params.from
Upvotes: 0