Home > OS >  using React Native prop onBackButtonPress?: () => void
using React Native prop onBackButtonPress?: () => void

Time:09-06

What is the correct chain of actions to use my prop onBackButtonPress?: () => void; ? Right now typescript shows an error for the onPress -

Type '(() => void) | undefined' is not assignable to type '() => void'.
  Type 'undefined' is not assignable to type '() => void'.

Do i need to type something completely different for the prop in my IconButton and app.tsx Header ?

type HeaderProps = {
    onBackButtonPress?: () => void;
};

export function Header({ onBackButtonPress }}: HeaderProps) {
    return (
            <View>
              <IconButton onPress={onBackButtonPress} />
            </View>
    );
}

app.tsx file

 <Header onBackButtonPress={() => null} />

CodePudding user response:

The issue is that the onPress prop of IconButton needs to receive the type () => void. However, onBackButtonPress is marked as optional, thus it could be undefined. These two types do not match.

In order to fix this, either allow onPress in IconButton to receive undefined or provide a dummy function if onBackButtonpress is undefined or do not mark onBackButtonPress as optional.

Not marked as optional

type HeaderProps = {
    onBackButtonPress: () => void;
};

In this case, the Header component cannot receive an undefined object for onBackButtonPress.

Create dummy function

onPress={onBackButtonPress ? onBackButtonPress : () => {}} />

This will just do nothing onPress if onBackButtonPress is undefined.

Change the type of IconButton

type IconButtonProps = {
    onPress?: () => void
}

export IconButton(props: IconButtonProps) {
   ...
}
  • Related