splunk
splunk

Reputation: 6805

Pass variable from one component to another one in react native

I have ChooseLevel component which has many buttons. Once I click a button onLevelSelected function is being called and it call action creator which will return an action type, moreover it will redirect me to qPage component. In qPage component I make some calculation and I put the result in total variable. Here's my code:

ChooseLevel.js

class ChooseLevel extends Component {
    constructor(props) {
        super(props);
    }
    onLevelSelected(levelNumber) {
        this.props.levelSelected(levelNumber);
    }

    render(){
      <Button key={1} onPress={this.onLevelSelected.bind(this, 1)}>
      <Button key={2} onPress={this.onLevelSelected.bind(this, 2)}>
      <Button key={3} onPress={this.onLevelSelected.bind(this, 3)}>
      ....
    }
}

My action creator looks like this:

import { Actions } from 'react-native-router-flux';
export const levelSelected = (levelNumber) => {
  return (dispatch) => {
      dispatch({
        type: 'level_selected', 
        payload: levelNumber
      });
      Actions.qPage();  // redirects me to qPage component 
  };
};

qPage.js

class qPage extends Component {
   constructor(props){
      ...
   }
   calc(){
       .... some calculation
       total = result of previous calculation 
   }
   render(){
     ....
     ....
   }
} 

How do I pass total variable from qPage to ChooseLevel page?

Upvotes: 1

Views: 2021

Answers (1)

Codesingh
Codesingh

Reputation: 3384

What you need to do is, i will go step by step:

1) create one more action and pass calculated value inside that action.

2) access that calculated value through props(reducer)

3) You can use componentWillUpdateProp(nextprops), Inside this fuction assign this new prop to the state of the class.

Cheers :)

Upvotes: 1

Related Questions