-1

I built a custom header for a screen in Drawer navigator because I need to add an Input on the Header, I need to access the value of the Input inside the screen but also the setState function because inside the screen it is possible to clear the input value

I tried wrapping my screen with context and access the context in the header to change the values but it didn't work.

const MyScreenContext = createContext(null);

Const MyScreenProvider = ({children})=>{
  const [state,setState] = useState("");
 return <MyScreenContext.Provider value={{state,setState}}>{children}</MyScreenContext.Provider>
}

const MyScreenHeader = ()=>{
 const context = useContext(MyScreenContext);
 // context here is null
}

const MyScreen = ()=>{
 

  return (
    <MyScreenProvider>
     ...
    </MyScreenProvider>
   )
};

And then I am adding them to the Drawer.Screen like this:

 <Drawer.Screen
        name={"MyScreen"}
        component={MyScreen}
        options={{
          header: MyScreenHeader,
        }}
  />
1
  • Can you share minimum reproducible example? Commented Dec 21, 2023 at 22:33

2 Answers 2

0

Wrap navigation container into a context provider. Only components inside can access a context. Something like this:

<MyScreenProvider>
  <NavigationContainer>
    <Drawer.Navigator>
      <Drawer.Screen
...
        options={{
          header: MyScreenHeader,
        }}
      />
    </Drawer.Navigator>
  </NavigationContainer>
</MyScreenProvider>

See SomeContext.Provider for details.

Sign up to request clarification or add additional context in comments.

1 Comment

I am surprised how react navigation doesn't have a built in solution for this
-1

You can use navigation.setOptions. https://reactnavigation.org/docs/header-buttons#header-interaction-with-its-screen-component

1 Comment

As it’s currently written, your answer is unclear. Please edit to add additional details that will help others understand how this addresses the question asked. You can find more information on how to write good answers in the help center.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.