roz333
roz333

Reputation: 715

How to use props and navigation together in one functional component in react native

I want to use props and {navigation} in one functional component in react-navigation version 5

This is my code:

const Header =(props, {navigation})=>{

return()}

But it doesn't work, I can't activate drawer. It returns following error :

undefined is not an object(evaluating 'navigation.openDrawer)

Upvotes: 0

Views: 3211

Answers (2)

Ahmed Khattab
Ahmed Khattab

Reputation: 2799

If your component is not registered as a route in routes object, you either have to pass the navigation prop manually, or you can do this. Because only the components that are registered as routes will have access to the navigation object.

Wrap it with withNavigation from react-navigation, like this:

import { withNavigation} from 'react-navigation'; 

const YourFunctionalComponent = props => { 
   // your component logic
};

// the navigation now will be in props
export default withNavigation(YourFunctionalComponent)

This works with any custom component deep in the tree.

Upvotes: 2

satya164
satya164

Reputation: 10152

You need to lookup destructuring: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Destructuring_assignment

Example:

const Header = (props)=> {
  const { navigation } = props;

  // Now you can use `navigation`
  // Instead of destructuring, you can also use `props.navigation`
}

Upvotes: 2

Related Questions