Search code examples
javascriptreactjsreact-nativereact-navigationreact-navigation-v5

React Native - How to use navigation on FlatList property?


I like to know how i can use React Navigation on FlatList property, where the name of the Stack.Screen comes from a .json file.

And with that, when the user click on that Item, they goes to another page of the application.

Data

{
  Data: [
    {
      "key": "0",
      "label": "Test",
      "goTo": "Test", <--- Here goes the name of Stack.Screen from routes.js
    }
  ]
}

FlatList structure

function Item({ label, goTo }) {
  return (
    <Ripple rippleCentered onPressIn={goTo}> // (react-native-material-ripple)
      <Option>
        <Icon name={onIcon} size={28} color={onColor} /> // (react-native-vector-icons)
        <OptionLabel color={onColor}>{label}</OptionLabel>
      </Option>
    </Ripple>
  );
}

I've already tried to use navigation.navigate({goTo}) on onPressIn property from Ripple, but a ReferenceError appears: Can't find variable: navigation

Final exported component

export default class Menu extends Component {
  render() {
    return (
      <Container color={this.props.color}>
        <FlatList
          data={Data}
          showsVerticalScrollIndicator={false}
          keyExtractor={item => item.key}
          numColumns={5}
          columnWrapperStyle={Styles.Row}
          renderItem={({ item }) =>
            <Item
              goTo={item.goTo}
              label={item.label}
            />
          }
        />
      </Container>
    );
  }
}

Solution

  • Read from json file

    import json from './myfile.json'; // reading from json file
    
    export default class Menu extends Component {
      render() {
        return (
          <Container color={this.props.color}>
            <FlatList
              data={json.Data} // accessing Data from json
              showsVerticalScrollIndicator={false}
              keyExtractor={item => item.key}
              numColumns={5}
              columnWrapperStyle={Styles.Row}
              renderItem={({ item }) =>
                <Item
                  goTo={item.goTo}
                  label={item.label}
                />
              }
            />
          </Container>
        );
      }
    }
    

    Navigating

    You could use useNavigation hook to call navigation.navigate(goTo)

    e.g.

    import { useNavigation } from '@react-navigation/native';
    
    function Item({ label, goTo }) {
      const navigation = useNavigation(); // navigation hook
    
      return (
        <Ripple rippleCentered onPressIn={() => navigation.navigate(goTo)}> // navigate to goTo screen
          <Option>
            <Icon name={onIcon} size={28} color={onColor} />
            <OptionLabel color={onColor}>{label}</OptionLabel>
          </Option>
        </Ripple>
      );
    }
    

    Please notice that Menu needs to be under NavigationContainer so useNavigation can work.