Leem.fin
Leem.fin

Reputation: 42622

showing custom component in header

On one screen, I would like to have a custom component to be shown on the header.

I tried:

 const MyScreen = ({route, navigation}) => {
  
  navigation.setOptions({
    headerTitle: props => {
      <MyComponent {...props} />;
    },
  });

  ...
 export default MyScreen;

But it shows blank like below:

enter image description here

To further verify the approach is correct, I also tried to simply show a text:

navigation.setOptions({
    headerTitle: props => {
      <Text {...props}> Hello </Text>;
    },
  });

It also shows blank in the header title area. What am I missing? How to show a custom component in the header?

(MyScreen is hosted by a stack navigator)

Upvotes: 2

Views: 573

Answers (1)

Valentin Briand
Valentin Briand

Reputation: 3683

The issue is that you are not returning the component, hence why it is not displayed.

You should either write:

const MyScreen = ({route, navigation}) => {
  
React.useLayoutEffect(() => {
  navigation.setOptions({
    headerTitle: props => {
      return <MyComponent {...props} />;
    },
  });
}, [navigation]);
  ...
export default MyScreen;

or for a more concise syntax:

const MyScreen = ({route, navigation}) => {
  
React.useLayoutEffect(() => {
  navigation.setOptions({
    headerTitle: props => <MyComponent {...props} />,
  });
}, [navigation]);
  ...
export default MyScreen;

You also need to use useLayoutEffect because you cannot update a component from inside the function body of a different component.
useLayoutEffect runs synchronously after a render but before the screen is visually updated, which will prevent your screen to flicker when your title is displayed.

By the way, since you seemingly don't need to use a function as props of your component, you could define this option directly in your navigator like so:

<Stack.Navigator>
  <Stack.Screen
    name="MyScreen"
    component={MyScreen}
    options={{ headerTitle: props => <MyComponent {...props} /> }}
  />
</Stack.Navigator>

Upvotes: 2

Related Questions