Vencovsky
Vencovsky

Reputation: 31693

How to override navigation options in functional component?

To override navigation options using class components, it would be something like

export default class SomeClass extends Component {

    static navigationOptions = ({ navigation }) => {
        return {
            title: navigation.getParam('headerTitle'),
        }
    }

    componentDidMount() {
        this.props.navigation.setParams({ headerTitle: someVariableThatComesFromExternalCall })
    }

    ...
}

But how can I do this using functional component??

export default function SomeFunctionalCompoenent({ navigation }) {

    // How and Where do I change the header title ?

    useEffect(() => { navigation.setParams({ headerTitle: someVariableThatComesFromExternalCall })})
    return (
        ...
    )
}

Upvotes: 10

Views: 8589

Answers (2)

tbergq
tbergq

Reputation: 734

Edit: Note that this answer was based on the current version at that time. The answer below might be more accurate based on your version:

You still need to define navigationOptions on your functional component. You do it like this:

export default function SomeFunctionalComponent({ navigation }) {
    useEffect(() => { 
        navigation.setParams({ 
            headerTitle: someVariableThatComesFromExternalCall 
        }) 
    }, [])
}

SomeFunctionalComponent.navigationOptions = ({ navigation }) => {
    return {
        title: navigation.getParam('headerTitle'),
    }
}

Upvotes: 21

Andy Lorenz
Andy Lorenz

Reputation: 3084

I've got a suspicion the accepted answer isn't for the currently latest version of react navigation (5), and it definitely doesn't work for this version, so here's a working example for @react-navigation/native v5.7.2 :

export default function SomeFunctionalComponent({ navigation }) {
  useLayoutEffect(() => { 
    navigation.setOptions({ 
      headerTitle: 'some other title',
    }) 
  }, [])
}

I've used this to access react context - to get the user's name and avatar so I can set a nice title bar for them. I've pasted in the code for this in case it helps anyone:

import React, { useContext, useLayoutEffect } from 'react';
import UserContext from '../context/UserContext';

const HomeScreen = ({ navigation }) => {

  const userContext = useContext(UserContext);

  useLayoutEffect(() => {
    navigation.setOptions({
      title : userContext.name,
      headerLeft : () => (
        <TouchableOpacity
          onPress={() => {
            navigation.openDrawer();
          }}
        >
          <FastImage
            style={styles.userPhoto}
            resizeMode={FastImage.resizeMode.cover}
            source={{ uri: userContext.avatar }}
          />
        </TouchableOpacity>
      ),
    });
  }, [ userContext ]);

  return (
    // etc
  );
}

Upvotes: 10

Related Questions