Search code examples
reactjsreact-nativeactionsheet

How can I press individual option in actionsheet in React Native?


I am still new to React Native. I have an actionsheet with two options and a cancel option. I am having trouble understanding how to make each option do something different when pressed.

My code:

import React, { useRef } from "react"
import ActionSheet from 'react-native-actionsheet'
import { View, Text, Pressable } from "react-native";
import Icon from 'react-native-vector-icons/FontAwesome';

const ActionSheet = () => {

  let actionSheet = useRef();
  let optionArray = ['Orange', 'Cherry', 'Cancel'];

  const showActionSheet = () => {
    actionSheet.current.show();
  }

  return (
    <View
      <Pressable onPress={showActionSheet}>
        <View>
          <Text>Choose Fruit</Text>
          <Icon name="angle-right" size={15}/>
        </View>
      </Pressable>
      <ActionSheet 
        ref={actionSheet}
        options={optionArray}
        cancelButtonIndex={2}
        onPress={{????}}
      />
    </View>
  );
};

What I'd like to do is navigate to a different screen when an option is pressed

Would appreciate any help. Thank you in advance!


Solution

  • The onPress function provides an index argument. Thus consider the following code snippet.

    const onActionSelect = (index) => {
    
        if (index === 1) {
          // first action pressed
        } else if (index === 2) {
          // second action pressed
        }
        // and so on
    }
    
    <ActionSheet 
            ref={actionSheet}
            options={optionArray}
            cancelButtonIndex={2}
            onPress={onActionSelect}
    />