How can I share state between header and screen in react navigation?

83 Views Asked by At

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,
        }}
  />
2

There are 2 best solutions below

1
user18309290 On

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.

1
Suman Saurabh On