Skip to content Skip to sidebar Skip to footer

Pass Value From View To View - React Native

I am a beginner in react native , I have been trying for several days to make a small app. But I was stuck in a very trivial thing. I am trying to pass the user's name from LoginPa

Solution 1:

You may need to set up your navigator a little differently than you have it here. Try setting up your renderScene method to be more configurable by using React.createElement:

renderScene={(route, navigator) => {
 returnReact.createElement(route.component, { ...this.props, ...route.passProps, navigator, route } );
}}

Then you can assign the ...route.passProps property to component. Take a look at the passsProps property below. You can then pass whatever properties you need to in this way:

this.props.navigator.push({
    component: Home,
    passProps: {
      username: this.state.username,
    }
})

I've set up a basic project with what you were trying to accomplish here, and am pasting the code for the app below. There's also a more comprehensive example with navigationBar here.

'use strict';

varReact = require('react-native');
var {
  AppRegistry,
  StyleSheet,
  Text,
  View,
  Navigator,
  TouchableHighlight,
  TextInput
} = React;

varLogin = React.createClass({

  getInitialState() {
    return {}
  },

  _goToHome() {
    this.props.navigator.push({
        component: Home,
        passProps: {
          username: this.state.username,
        }
    })
  },

  updateUsername(username) {
    this.setState({ username })
  },

    render() {
      return (
        <Viewstyle={styles.container}><TouchableHighlightonPress={ () => this._goToHome() }
            style={ styles.button }>
            <Text>
                GO TO ABOUT
            </Text></TouchableHighlight><TextInputonChangeText={ (username) => this.updateUsername(username) }
            placeholder="Your Username"
            style={ styles.input }
          />
       </View>
     )
   }
})

varHome = React.createClass({
    render() {
      return (
        <Viewstyle={styles.container }><Text>Hello, { this.props.username }</Text></View>
      )
    }
})

varApp = React.createClass({  
  render() {
    return (
      <NavigatorinitialRoute={{name: 'Login', component:Login, index:0}}
      renderScene={(route,navigator) => {
        return React.createElement(route.component, { ...this.props, ...route.passProps, navigator, route } );
      }} />
    );
  }
});

var styles = StyleSheet.create({
  container: {
    flex: 1,
    marginTop: 60
  },
  button: {
    height: 60,
    backgroundColor: '#ededed',
    justifyContent: 'center', 
    alignItems: 'center'
  },
  input: {
    backgroundColor: '#f7f7f7',
    marginTop:10,
    borderWidth:1, 
    borderColor: '#ededed',
    height:60
  }
});

AppRegistry.registerComponent('App', () =>App);

Post a Comment for "Pass Value From View To View - React Native"