Pedro Gonzalez
Pedro Gonzalez

Reputation: 95

Passing state array from class into function with pure react native

I am fetching rest api and saving it into array jsonData in App class and because I implemented react-navigation, I want to display its content outside this class, in a function. I read multiple times to use redux, but I am complete react native beginner and the only thing I need to use state for is one array with things I need to display. I am not doing anything complicated so I am confused why is it so hard to pass one array to a function.

export default class App extends Component {
state = {
    jsonData: [],
};
componentDidMount() {
    fetch('https://pokeapi.co/api/v2/pokemon/ditto/', {
        method: 'GET',
    })
        .then(response => response.json())
        .then(json => {
            this.setState({
                jsonData: JSON.stringify(json),
            });
        })
        .catch(error => {
            console.error(error);
        });
}
render() {
    return (
        <NavigationContainer>
            <Drawer.Navigator initialRouteName="Home">
                <Drawer.Screen name="Home" component={HomeScreen}/>
                <Drawer.Screen name="Notifications" component={NotificationsScreen} />
            </Drawer.Navigator>
        </NavigationContainer>
    );
}}

Here I control what to show after clicking on Home screen, obviously, I cant print it like I do here. I tried searching stackoverflow with answers suggesting to use constructor with props, but these solutions did not work for me.

function HomeScreen() {
    return (
            <View>
            <Text>this.state.jsonData</Text>
            </View>
    );
}

What do I need to change in my code to pass the array to the Homescreen function without using redux-like libraries?

Upvotes: 1

Views: 522

Answers (1)

Ketan Ramteke
Ketan Ramteke

Reputation: 10655

You can do it this way:

render() {
    return (
        <NavigationContainer>
            <Drawer.Navigator initialRouteName="Home">
                <Drawer.Screen name="Home" component={() => <HomeScreen data={this.state.jsonData}/>}/>
                <Drawer.Screen name="Notifications" component={NotificationsScreen} />
            </Drawer.Navigator>
        </NavigationContainer>
    );

}}


function HomeScreen({data}) {
    return (
            <View>
            <Text>{JSON.stringify(data)}</Text>
            </View>
    );
}

Upvotes: 1

Related Questions