Use 'gorhom/bottom-sheet' React Native, Hooks can only be called inside of the body of a function component

Viewed 1196

I'm having a in react native which cannot call function component of gorhom/bottom-sheet and import to another component. Below is my code and error.

Function Component

import React, {useCallback, useMemo, useRef} from 'react';
import {View, Text, StyleSheet, Button} from 'react-native';
import {BottomSheetModal, BottomSheetModalProvider} from '@gorhom/bottom-sheet';

const BottomModal = () => {
  const snapPoints = useMemo(() => ['25%', '50%'], []);

  // ref
  const bottomSheetModalRef = useRef<BottomSheetModal>(null);

  // variables

  // callbacks
  const handlePresentModalPress = useCallback(() => {
    bottomSheetModalRef.current?.present();
  }, []);

  const handleSheetChanges = useCallback((index: number) => {
    console.log('handleSheetChanges', index);
  }, []);

  // renders
  return (
    <BottomSheetModalProvider>
      <View style={styles.container}>
        <Button
          onPress={handlePresentModalPress}
          title="Present Modal"
          color="black"
        />
        <BottomSheetModal
          ref={bottomSheetModalRef}
          index={1}
          snapPoints={snapPoints}
          onChange={handleSheetChanges}>
          <View style={styles.contentContainer}>
            <Text>Awesome </Text>
          </View>
        </BottomSheetModal>
      </View>
    </BottomSheetModalProvider>
  );
};

const styles = StyleSheet.create({
  container: {
    flex: 1,
    padding: 24,
    justifyContent: 'center',
    backgroundColor: 'grey',
  },
  contentContainer: {
    flex: 1,
    alignItems: 'center',
  },
});

export default BottomModal;

Import it to use in another function component

          <TouchableOpacity onPress={BottomModal}>
            <Icon
              size={28}
              style={{marginRight: 20, color: Colors.grey2, marginTop: 16}}
              name="calendar-outline"
            />
          </TouchableOpacity>

Error Invalid hook call. Hooks can only be called inside of the body of a function component. This could happend for one of the following reasons

1 Answers

The onPress function for the TouchableOpacity seems to be a problem here. Use some state to show or hide the BottomModel accordingly

const [isBottomModalOpen, setIsBottomModalOpen] = useState(false);

And then for the Touchable Opacity you set the state to be true and render the Modal

<TouchableOpacity onPress={BottomModal}>
    <Icon
      size={28}
      style={{marginRight: 20, color: Colors.grey2, marginTop: 16}}
      name="calendar-outline"
    />
</TouchableOpacity>

And then render the Modal conditionally if the setIsBottomModalOpen state is set to true

Related