My goal is to dynamically generate tabs in React-Navigation based on the values retrieved from an array, and pass the data from each array value to the corresponding screen. For instance, if there are 2 accounts, I expect 2 tabs with unique screens for each, and if there are 5 accounts, there should be 5 tabs with their respective screens generated based on the database values.
Here is what I have tried so far:
interface Account {
accountNumber: string;
balance: number;
}
const accounts: Account[] = [
{ accountNumber: '1', balance: 10 },
{ accountNumber: '2', balance: 15 },
{ accountNumber: '3', balance: 20 }
];
class AccountScreen extends React.Component<Account>{
constructor(props: Account) {
super(props)
}
render() {
return (
<View>
<Text>This is an Account</Text>
<Text>Account Number: {this.props.accountNumber}</Text>
<Text>Balance: £{(this.props.balance/100).toFixed(2)}</Text>
</View>
);
}
};
const accountScreens = {};
accounts.forEach(account => accountScreens[account.accountNumber] = { screen: AccountScreen, props: account });
// SOMETHING LIKE THIS
export default AccountNavigator = createMaterialTopTabNavigator(accountScreens);
While the screens display with the appropriate tabs, the data within each account is not being passed through props. I understand that props cannot be passed directly into the Navigator, but I am unsure of how to make that data accessible to the component. Is there a fundamental flaw in my approach, or is there a syntactic issue that I am overlooking?
Thank you for your assistance!
Solution:
I discovered that the props can be accessed by returning a function to the screen key in the navigator.
Here is the final solution that resolved the issue for me:
accounts.forEach(account => {
accountScreens[account.accountNumber] = {screen: (props) => {
return <AccountScreen accountNumber={account.accountNumber} {...props} />}
}
})