typescriptreact-nativereact-navigationreact-navigation-stack

React-Navigation update a header icon from itself


I am trying to update a header icon using itself. I have a heart icon in the headerRight component:

const [enabled, setEnabled] = useState(false);

navigation.setOptions({
   headerRight: () => (<TouchableOpacity onPress={() => setEnabled(prev => !prev)}>{enabled ? <HeartFill/> : <HeartOutline/>}</TouchableOpacity>)
});

But this doesn't work since navigation.setOptions() is never 're-called' to update to the correct icon. How can I make a child update itself in react-navigation?

Instead of setEnabled I could pass navigation.setOptions() again but that would just make me do some endless nesting if I want to toggle between more than 2 states.


Solution

  • If you want to keep it pure, could you try this?

    const Parent = () => {
      navigation.setOptions({
        headerRight: () => <Child /> 
      })
    
      return null
    }
    
    const Child = () => {
      const [enabled, setEnabled] = useState(false);
      
      return (
        <TouchableOpacity 
          onPress={() => setEnabled(prev => !prev)}>{enabled ? <HeartFill/> : <HeartOutline/>}
        </TouchableOpacity>
      )
    }