Benjamin Smith Max
Benjamin Smith Max

Reputation: 2748

How to pass default params to each routes in react navigation

I have this router config:

export const Bird = StackNavigator({
    ResidentBirds: {
        screen: BirdList,
        navigationOptions: ({navigation}) => ({
            title: 'Resident Birds',
        })
    },
    MigratoryBirds: {
        screen: BirdList,
        navigationOptions: {
            title: 'Migratory Birds'
        }
    }
});

Both the routes have the same screen component (BirdList).

BirdList.js:

export default class BirdList extends React.Component {
    state = {
        fetching: false,
        dataSource: []
    };

    componentDidMount() {
        this.getBirds();
    }

    getBirds = () => {
        // const birdType = this.props.navigation.state.params.birdType;
        // const args = this.pros.navigation.state.params.args;

        // fetch list of birds of type birdType
    };

    render() {
        return (
            <View style={{flex: 1, backgroundColor: 'skyblue'}}>
                <Text>Fetching birds: {this.state.fetching.toString()}</Text>
                <FlatList
                    data={this.state.dataSource}
                    ...
                />
            </View>
        )
    }
}

App.js:

import {Bird} from './src/config/router'
export default class App extends React.Component {
    ...

    render() {
        return <Bird/>
    }
}

My question is how can I pass default params to the Routes (i.e., ResidentBirds and MigratoryBirds) so that I can use that values to fetch appropriate data?

Maybe something like this:

export const Bird = StackNavigator({
    ResidentBirds: {
        screen: BirdList,
        navigationOptions: ({navigation}) => ({
            title: 'Resident Birds',
        }),
        params: {
            birdType: 'Resident',
            args: {
                'height': 100,
                'region': 'America'
            }
        }
    },
    MigratoryBirds: { 
        ...
    }
});

Upvotes: 0

Views: 3094

Answers (1)

Benjamin Smith Max
Benjamin Smith Max

Reputation: 2748

Working solution by Spencer in github:

export const Bird = StackNavigator({
    ResidentBirds: {
        screen: (props) => <BirdList {...props} birdType="Resident" args={{ height: 100, region: 'America' }} />,
        navigationOptions: ({navigation}) => ({
            title: 'Resident Birds',
        })
    },
    ...
});

Upvotes: 5

Related Questions