react-native update NavigatorIOS component's props

796 views Asked by At

I have the following code in which HomeTab contains a NavigatorIOS. I'm passing HomeScreen as the component for the navigator.

I have some events happening on a parent component that contains HomeTab and would like to pass them to HomeScreen. I am able to get the to HomeTab. How can I set the props or state for the component and preferably, I'd like to be able to call a function on it. Any clue?

class HomeTab extends React.Component {
  constructor() {
    super()
    this.state = {}
  }

  render() {
    return (
        <NavigatorIOS style={styles.container}
            initialRoute={{
              title: 'Home',
              component: HomeScreen,
              passProps: {}
            }}
        />
    )
  }
}
2

There are 2 answers

3
Mahdi Yusuf On

You can simply pass them through that passProps object there.

I think you might be missing the other piece in your HomeScreen component.

var HomeScreen = React.createClass({

    propTypes: {
        text: React.PropTypes.string.isRequired,
    },

Then in your root view you would do

class HomeTab extends React.Component {
  constructor() {
    super()
    this.state = {}
  }

  render() {
    return (
        <NavigatorIOS style={styles.container}
            initialRoute={{
              title: 'Home',
              component: HomeScreen,
              passProps: {text: 'Woot!'}
            }}
        />
    )
  }
}

N.B. that if you provide the isRequired that your code will slam to a halt if you don't provide it when you display/push HomeScreen.

1
Philipp von Weitershausen On

Yeah, the navigator model breaks the React-y dataflow (as I've outlined in this answer, too: What is the right way to save data from a list view?)

IMHO best way to achieve what you're trying to do is to have this Geolocation service provide a global subscription functionality that your HomeScreen component subscribes to. E.g. using the Geolocation module's API that ships with React Native:

class HomeScreen extends React.Component {
  constructor(props) {
    super(props);
    this.state = {locationInfo: {...}};
    this._watchID = Geolocation.watchPosition(
      (locationInfo) => {this.setState({locationInfo});},
      (error) => {...},
      ...
    );
  }

  componentWillUnmount() {
    Geolocation.clearWatch(this._watchID);
  }

  render() {
    ...
  }
}

If you're using some sort of custom location service in between the device APIs and your app, then I would model a similar API for that service. You could for instance use the EventEmitter library that ships with React Native.

Now, if you absolutely must get an instance of HomeScreen from HomeTab, then that's possible too, using the ref prop, as I've outlined in this answer: Function to call onRightButtonPress in NavigatorIOS - React Native