Maja Okholm
Maja Okholm

Reputation: 3337

How to pass state to component React Native

I am new to React Native and really cant figure out why I am not able to pass a state from one component to another

export default class questions extends Component {
constructor(props){
    super(props);
    this.state={
        name: "stupidCount",
        val: 1}            
}

render(){
    const { navigate } = this.props.navigation;
    const { name2 } = this.state;
    return(
        <View style={styles.box}>
            <TouchableOpacity onPress={() => navigate('Question1',  stupidCount={name2})} >
                <Text style={styles.h1}> Question 1 </Text>
            </TouchableOpacity>

Second component, 'Question1'

export default class Question2 extends Component {
render(){
    const { navigate } = this.props.navigation;
    console.log(stupidCount.val);
    return(
        <View style={styles.box}>
            <Text style={styles.h1}>Question 2 </Text>
            <Text> state test {stupidCount.val}</Text>

Thanks a lot in advance

Upvotes: 3

Views: 5061

Answers (1)

Chirag Shah
Chirag Shah

Reputation: 640

I think you are using react-navigation. If yes, then the following changes need to made to access value of stupidCount in Question2 component.

In questions component,

state should be set as:

this.state={
  stupidCount: 1,
}

onPress should be handled as

onPress={() => navigate('Question1', { stupidCount: this.state.stupidCount } )}

and in Questions2 component, you can access the value as:

this.props.navigation.state.params.stupidCount

Upvotes: 6

Related Questions