Home > Back-end >  React Native - Allow only Touchable/Pressable components as prop
React Native - Allow only Touchable/Pressable components as prop

Time:10-18

I want to create a component MyComponent that receives a prop called component of type React.ElementType. My goal is to restrict the component prop to only Components that have a valid implementation for the onPress prop, so I just want to allow Pressable components like Button, Touchables, Pressables, etc.

How can I achieve this from typescript to get a proper declaration? And how can I check if the component passed into the prop has an onPress implementation so I can throw an error if not??

interface MyComponentProps {
  // Allow only Components that have implementation
  // for onPress like TouchableOpacity,
  // TouchableWithoutFeedback or Pressable

  component: React.ElementType;
}

const MyComponent: React.FC<MyComponentProps> = (props) => {
  const {
    component: Component,
    children
  } = props;

  // How to check if Component is a valid component that implements onPress??
  // So if not I can throw an error before render

  const myOnPress = () => {};

  return (
    <View>
      <Component onPress={myOnPress} />
      <View>{children}</View>
    </View>
  );
}

CodePudding user response:

In order to have Typescript validate the prop at compile time, use generics to narrow down the ElementType like so:

type Props = {
  component: React.ElementType<{onPress: (...args?: any[]) => void}>
}

You might want to make the type of arguments more or less specific, depending on your needs (eg by making the return value any).

  • Related