Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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

>Solution :

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) {
   ...
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading