Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to set navigationOptions on stateless component with Typescript

I have a react component like

const Example = () => (<View>...</View>);

Using react-navigation I would normally apply navigation options by saying

Example.navigationOptions = { options };

With typescript I am getting the error

[ts] Property 'navigationOptions' does not exist on type '(props: Props) => Element'.

How can I fix this?

I tried writing an interface

interface ExampleWithNavigationOptions extends Element {
    navigationOptions?;
}

But with no luck.

like image 526
xerotolerant Avatar asked Mar 05 '18 18:03

xerotolerant


People also ask

Can stateless components have props?

A component can be stateless and only use the props values passed to it. These values can either contain references to a calling component's state values or references to a calling component's method.

What is static navigationOptions?

A screen component can have a static property called navigationOptions which is either an object or a function that returns an object that contains various configuration options. The one we use for the header title is title , as demonstrated in the following example. class HomeScreen extends React.


2 Answers

You can use the following:

import {
  NavigationScreenProps,
  NavigationScreenComponent
} from 'react-navigation'

interface Props extends NavigationScreenProps {
  // ... other props
}

const MyScreen: NavigationScreenComponent<Props> = ({ navigation }) => {
  // ... your component
}

MyScreen.navigationOptions = {
  // ... your navigation options
}

export default MyScreen

like image 95
Sat Mandir Khalsa Avatar answered Oct 18 '22 15:10

Sat Mandir Khalsa


The key idea is to specify correct type for Example constant. Probably, react-navigation already provides that type. But, you can also extend build-in React interface smth like this:

    interface NavStatelessComponent extends React.StatelessComponent {
        navigationOptions?: Object
    }

    const Example: NavStatelessComponent = () => {
        return (
            <View>
               ...
            </View>
        )
    }

    Example.navigationOptions = {
        /*
        ...
        */
    }

    Example.propTypes = {
        /*
        ...
        */
    }
like image 39
Bob Avatar answered Oct 18 '22 16:10

Bob