Search code examples
react-nativereact-native-router-flux

react-native-router-flux. How to change custom navBar programmatically?


I have a custom navBar in my scene:

<Scene key="myPage"
    component={MyPage}
    navBar={NavBarCustom}
    hideNavBar={false}/>

....

class NavBarCustom extends Component {

  constructor(props) {
      super(props);
  }

  onExitPressed(){
    App.exit();
  }

  render() {
    return (
      <View style={styles.navBar}>

        <View style={styles.leftContainer}>
          <Image 
            style={styles.logo} 
            source={require('./../../res/ic_nav_bar.png')}/>
          <Text style={[appStyles.customFontBold, styles.title1]}>
            MY TITLE
          </Text>
        </View>

        <View style={styles.centralContainer}>
          <Text style={[appStyles.customFontRegular, styles.title2]}>
            {strings.benefit_identifier}
          </Text>
        </View>

        <View style={styles.rightButtonContainer}>
          <TouchableHighlight
            style={{padding: 7}}
            underlayColor='#b59d6e'
            onPress={() => { this.onExitPressed() }}>
            <Text style={[appStyles.customFontRegular, styles.rightButtonTitle]}>
              {strings.exit}
            </Text>
          </TouchableHighlight>
        </View>

      </View>
    );
  }
}

It works good. So how can I change title1 of NavBarCustom from my scene MyPage?

Thanks in advance.


Solution

  • You can pass/send information through/with props:

    In your render you can declare a const which take the react-native-router-flux Actions, set the route which to point and then set the object which to pass:

    If there's a Login main file, which then redirects to a Register view then you declare the const goToRegister and then pass the text with its content:

    class Login extends Component {
      render() {
        const goToRegister = () => Actions.Register({text: 'From Login'}); 
        return(
          <View style={{flex:1}}>
            <Text>
              Login
            </Text>
            <TouchableHighlight onPress={goToRegister} style={{ marginTop: 100}}>
              <Text>Go Register</Text>
            </TouchableHighlight>
          </View>
        )
      }
    }
    

    Then within your Register you receive it just within your props as this.props.text:

    class Register extends Component {
      render() {
        return(
          <View style={{flex:1}}>
            <TouchableHighlight onPress={Actions.Login} style={{ marginTop: 100}}>
             <Text>{ this.props.text }</Text>
            </TouchableHighlight>
          </View>
        )
      }
    }
    

    In your case you should send firstly the value of your title maybe as:

    render() {
      const goToMyPage = () => Actions.MyPage({ title: 'Some Title'})
      ...
    

    And then you're able to use it:

    <Text style={[appStyles.customFontBold, styles.title1]}>
      { this.props.title }
    </Text>