Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I pass dispatch function into Header Component?

import React from 'react'
import {
  StackNavigator
} from 'react-navigation'

import Home from './Home'
import Detail from './Detail'
import MyIcon from './MyIcon'

export default StackNavigator({
  Home: {
    screen: Home,
    navigationOptions: {
      title: 'Foo',
      headerRight: (<MyIcon dispatch={}/>), //<- Here
    }
  },
  Detail: {
    screen: Detail,
    navigationOptions: {},
  },
})

I want to pass dispatch function into HeaderComponent like headerRight in React Navigation Option setting. How can I do this?

like image 486
Tomy Avatar asked Jan 08 '18 09:01

Tomy


1 Answers

You need to call your dispatch function in headerRight and set when your component is mounted using this.props.navigation.setParams

import React from 'react'
import {
    StackNavigator
} from 'react-navigation'

import Home from './Home'
import Detail from './Detail'
import MyIcon from './MyIcon'

export default StackNavigator({
    Home: {
        screen: Home,
        navigationOptions: ({ navigation }) => {
            title: 'Foo',
            headerRight: (<MyIcon 
                          onPress={ () => navigation.state.params.dispatch() } />)
                          // calling dispatch when headerRight icon is press
        }
    },
    Detail: {
        screen: Detail,
        navigationOptions: {},
    },
})

Set dispatch function in your component

...

//setting dispatch function to headerRight in your component
componentDidMount() {
    this.props.navigation.setParams({
        dispatch: this.dispatch.bind(this)
    });
}

dispatch() {
    // your code
}

I hope this helps!

like image 149
Ahsan Ali Avatar answered Nov 14 '22 19:11

Ahsan Ali