Home > Net >  How to close the custom dropdown from outside the dropdown component?
How to close the custom dropdown from outside the dropdown component?

Time:10-27

I am using a Dropdown which is basically like below on many screens in the app. As you can see, on the screens I use this dropdown, the dropdown becomes 50 height when clicked and 20 when clicked again. On the screens where I use this dropdown, if the dropdown is on (height is 50), I want it to close when clicked somewhere other than the dropdown on the screen. Since I use the dropdown on so many screens, I only want to do this inside the dropdown component. How can I do that?

import React, { useState } from 'react';
import { View, TouchableOpacity } from 'react-native';


export default Dropdown = () => {

  const [isOpen, setIsOpen] = useState(false);

  return (
    <View
      style={{ backgroundColor: "grey" }}>
      <TouchableOpacity
        style={{ height: 20, width: 200 }}
        onPress={() => setIsOpen(prev => !prev)}>
      </TouchableOpacity>
      <View style={{
        display: isOpen ? 'flex' : 'none',
        height: 50
      }}>
      </View>
    </View>
  );
};

How to close the custom dropdown from outside the dropdown component

CodePudding user response:

You can use a modal to show the drawer contents. In this way, you can easily close the drawer on the screens where it is used.

import React, { useRef, useState } from 'react';
import { View, TouchableOpacity, Modal, TouchableWithoutFeedback, Text } from 'react-native';


export default Dropdown = () => {

  const [isOpen, setIsOpen] = useState(false);
  const [dropdownFrame, setDropdownFrame] = useState(null)
  const dropdownRef = useRef()

  const onPress = () => {
    if (dropdownRef.current && dropdownRef.current.measure) {
      dropdownRef.current.measure((fx, fy, width, height, x, y) => {
        // required dropdown measure to display content directly below the dropdown
        setDropdownFrame({ width, height, x, y })
        setIsOpen(true)
      })
    }
  }

  return (
    <View>
      {/* drawer title */}
      <TouchableOpacity
        style={{ height: 30, backgroundColor: "grey" }}
        onPress={onPress}
        ref={dropdownRef}
      >
        <Text>Drawer Title</Text>
      </TouchableOpacity>
      {/* drawer content */}
      {isOpen &&
        <Modal transparent>
          <TouchableWithoutFeedback onPress={() => setIsOpen(false)}>
            <View style={{ flexGrow: 1 }}>
              <View style={{
                height: 40,
                backgroundColor: "red",
                top: dropdownFrame.y   dropdownFrame.height,
                left: dropdownFrame.x,
              }} >
                <Text>item</Text>
              </View>
            </View>
          </TouchableWithoutFeedback>
        </Modal>}
    </View>
  );
};

CodePudding user response:

May be you need react-native-modal-dropdown

  • Related